2012-03-02 5 views
1

내 사이트에 양식이 있습니다. 제출 버튼을 클릭하면 함수가 실행되어 각 필드의 내용을 가져 와서 RegEx 및 기타 요구 사항에 따라 내용의 유효성을 검사 한 다음 모든 것이 정상적으로 보일 경우 양식이 Ajax를 통해 .php 메일러로 제출됩니다.Javascript 입력 변경시 유효성 확인, 제출 버튼 클릭시 제출

양식이 입력 필드 값이 변경 될 때 자동으로 유효성을 검사하거나 입력 필드가 포커스를 잃을 때 (나는 기본 설정이 없거나 중대 할 때) 양식을 제출할 때만 양식을 제출하기를 원합니다. 사용자가 양식의 제출 단추를 클릭합니다. 모든 필드가 유효하기 전에 사용자가 제출 버튼을 클릭하면 양식을 제출하고 싶지 않습니다.

여기 내 코드입니다 :

//contact form validation 
$(function(){ 
    $('.error').hide(); 
    // hide error messages onchange 
    $("#contact-form").change(function(){ 
     $('.error').hide(); 
     $("label#name_error").hide(); 
     $("label#invalid_error").hide(); 
     $("label#email_error").hide(); 
     $("label#invalid_phone_error").hide(); 
     $("label#phone_error").hide(); 
     $("label#zip_error").hide(); 
    }); 

    // validate fields on click 
    $(".cool-button").click(function(){ 
     $('.error').hide(); 
     $("label#name_error").hide(); 
     $("label#invalid_error").hide(); 
     $("label#email_error").hide(); 
     $("label#invalid_phone_error").hide(); 
     $("label#phone_error").hide(); 
     $("label#zip_error").hide(); 

     var name=$("input#contact_name").val(); 
     var email=$("input#contact_email").val(); 
     var emailRegEx =/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/ 
     var phone=$("input#contact_phone").val(); 
     var phone=phone.replace(/\s+-/g, ""); 
     var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/ 
     var zip=$("input#contact_zip").val(); 
     var best_time=$("input#contact_best_time").val(); 
     var message=$("textarea#contact_message").val(); 
     var timestamp=$("input#timestamp").val(); 

     if(name==""){ 
      $("label#name_error").show(); 
      $("input#contact_name").focus();return false; 
      } 
     if(email==""){ 
      $("label#email_error").show(); 
      $("input#contact_email").focus();return false; 
      } 
     if (document.getElementById('contact_email').value.search(emailRegEx)==-1) { 
      $("label#invalid_error").show(); 
      $("input#contact_email").focus();return false; 
      } 
     if(phone==""){ 
      $("label#phone_error").show(); 
      $("input#contact_phone").focus();return false; 
      } 
     if (document.getElementById('contact_phone').value.search(phoneRegEx)==-1) { 
      $("label#invalid_phone_error").show(); 
      $("input#contact_phone").focus();return false; 
      } 
     if(zip==""){ 
      $("label#zip_error").show(); 
      $("input#contact_zip").focus();return false; 
      } 
     if(message==""){ 
      $("label#message_error").show(); 
      $("textarea#contact_message").focus();return false; 
      } 
     else { 
var dataString='contact_name='+name+'&contact_email='+email+'&contact_phone='+phone+'&contact_zip='+zip+'&contact_best_time='+best_time+'&timestamp='+timestamp+'&contact_message='+encodeURIComponent(message); 
    $.ajax({ 
     type:"POST", 
     url:"php/contact.php", 
     data:dataString, 
     success:function(){$('#contact-form').html("<div id='message'></div>");$('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at [email protected] or call us at 800-924-9473</p>").hide().fadeIn(800,function(){$('#message').append("<img id='checkmark' src='images/submit2.png' />");});}}); 
     } 
     return false; 
    }); 

}); 

여기에 양식

<form id="contact-form" method="post" action="#"> 
          <p class="form-subscr-field"> 
          <label for="contact_name" id="contact_name_label">Your name: *</label> 
          <input id="contact_name" type="text" name="contact_name" class="inputbox" size="10" required/> 
          <label class="error error-tip" for="contact_name" id="name_error" style="display: none; ">Please enter your name.</label> 
          </p> 
          <p class="form-subscr-field"> 
          <label for="contact_email" id="contact_email_label">E-mail Address: *</label> 
          <input id="contact_email" type="email" name="contact_email" class="inputbox" size="10" required/> 
          <label class="error error-tip" for="contact_email" id="email_error" style="display: none; ">Please enter your email address.</label> 
          <label class="error error-tip" for="contact_email" id="invalid_error" style="display: none; ">Invalid email address.</label> 
          </p> 
          <fieldset class="w50"> 
          <p class="form-subscr-field rowElem left"> 
          <label for="contact_phone" id="contact_phone_label">Phone: *</label> 
          <input id="contact_phone" type="tel" name="contact_phone" class="inputbox" size="10" required minlength="9"/> 
          <label class="error error-tip" for="contact_phone" id="phone_error" style="display: none; ">Please enter your phone number.</label> 
          <label class="error error-tip" for="contact_phone" id="invalid_phone_error" style="display: none; ">Please enter a valid phone number.</label> 
          </p> 
          </fieldset> 
          <fieldset class="w50"> 
          <p class="form-subscr-field rowElem right"> 
          <label for="contact_zip" id="contact_zip_label">Zip Code: *</label> 
          <input id="contact_zip" type="text" name="contact_zip" class="inputbox" size="10" required minlength="5"/> 
          <label class="error error-tip" for="contact_zip" id="zip_error" style="display: none; ">Please enter your shipping zip code.</label> 
          </p> 
          </fieldset> 
          <p class="form-subscr-field"> 
          <label for="contact_best_time" id="contact_best_time_label">Best time to Contact:</label> 
          <input id="contact_best_time" type="text" name="contact_best_time" class="inputbox" size="10" /> 
          </p> 
          <p class="form-subscr-field"> 
          <label for="contact_message" id="comment_label">Your message: *</label> 
          <textarea id="contact_message" name="contact_message" rows="8" cols="30" required minlength="2"></textarea> 
          <label class="error error-tip" for="contact_message" id="message_error" style="display: none; ">This field is required.</label> 
          </p> 
          <input type="hidden" id="timestamp" name="timestamp" value="<?php 
$hourdiff = "2"; // hours diff btwn server and local time 
$insertdate = date("l, d F Y h:i a",time() + ($hourdiff * 3600)); 
print ("$insertdate"); 
?>" /> 
          <div class="submit-contact"> 
          <p> 
           <input type="submit" name="submit" class="cool-button csbutton-color spot-action" id="contact_button" value="Submit" /> 
          </p> 
          </div> 
         </form> 
+0

그냥 호기심; 서버에서도 유효성을 검사 할 수 있습니까? –

+0

즉시 확인하는 문제는 아직 값이없는 필드에 대해 오류를 표시한다는 것입니다. 수동으로 어느 것이 추악 할 지, 아니면 일종의 플러그인/라이브러리 (당신이 직접 작성할 수있는)로 이것을 깨뜨려야합니다. –

+0

@ 제필 : 귀하의 질문을 이해할 수 있도록 서버에서 유효성 검사가 무엇을 의미하는지 설명하십시오. – adamdehaven

답변

0

당신은 검증 플러그인의 어떤 종류를 사용해야에 대한 HTML과 PHP 코드입니다. 개인적으로 나는 jquery 도구를 validator 형식으로 사용했으며 훌륭한 결과를 얻었습니다. 다른 것들도 있습니다. 이 옵션을 선택합니다 : http://flowplayer.org/tools/validator/

나는 또한 내가 형태를 취할와 아약스를 통해 제출, 거기에 약간의 거기 밖으로 내에 실제 비슷한 일을하는 것이다 내장 플러그인을 사용

:

http://jquery.malsup.com/form/

하나의 예입니다. 이렇게하면 일반 html로 양식을 만들 수 있으며 양식의 작업 URL에 양식을 제출하고 아약스없이 제출 한 경우 브라우저와 동일한 방식으로 양식 값을 작성합니다. 따라서 백엔드 스크립트가 무엇이든 아약스를 사용하지 않은 것처럼 양식 필드가 제출됩니다.

이 코드는 너무 많은 작업으로 보이므로 코드의 유무에 관계없이 코드의 모습을 보여 드리겠습니다.

(귀하의 j를 살펴보십시오.)

없음 가정 양식

이 (간체)과 같은

<form method="POST" action="php/contact.php"> 
    <label for="contact_name">Name</label> 
    <input name="contact_name" id="contact_name" /> 
    <br /> 
    <label for="contact_email">Email</label> 
    <input name="contact_email" id="contact_email" /> 
    <br /> 
    <label for="contact_phone">Phone</label> 
    <input name="contact_phone" id="contact_phone" /> 
    <br /> 
    <label for="contact_zip">Zip</label> 
    <input name="contact_zip" id="contact_zip" /> 
    <br /> 
    <label for="contact_best_time">Best time for Contact</label> 
    <input name="contact_best_time" id="contact_best_time" /> 
    <br /> 
    <label for="contact_message">Message:</label> 
    <input name="contact_message" id="contact_message" /> 
</form> 

지금은 형식에 대한 모든 여분의 HTML없이 지금의 모습에 아마 비슷한 이잖아.

유효성 검사기와 ajax 양식 검사기를 모두 사용한 경우 변경 사항을 거의 작성하지 않아야합니다. 보여 드리죠.

<form method="POST" action="php/contact.php" class="use-validator ajax-form"> 
    <label for="contact_name">Name</label> 
    <input name="contact_name" id="contact_name" /> 
    <br /> 
    <label for="contact_email">Email</label> 
    <input name="contact_email" id="contact_email" type="email" required="required" /> 
    <br /> 
    <label for="contact_phone">Phone</label> 
    <input name="contact_phone" id="contact_phone" type="phone" /> 
    <br /> 
    <label for="contact_zip">Zip</label> 
    <input name="contact_zip" id="contact_zip" required="required" /> 
    <br /> 
    <label for="contact_best_time">Best time for Contact</label> 
    <input name="contact_best_time" id="contact_best_time" required="required" /> 
    <br /> 
    <label for="contact_message">Message:</label> 
    <textarea name="contact_message" id="contact_message" required="required"></textarea> 
</form> 

이 그런 다음 JS은 다음과 같습니다 :

$.tools.validator.fn("[type=phone]", "Invalid phone number", function(input, value) { 
    var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/ 
    return value.test(phoneRegEx); 
}); 

$("form.use-validator").validator(); 

$("form.ajax-form").ajaxForm({ 
success:function(){$('#contact-form').html("<div id='message'></div>");$('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at [email protected] or call us at 800-924-9473</p>").hide().fadeIn(800,function(){$('#message').append("<img id='checkmark' src='images/submit2.png' />");});}}); 
}); 

을 그리고 사용자 정의 당신이 다른 형태에 재사용 할 수 있도록 유효성 검사기 .. 발리와 아약스 형태로

그런 다음이있을 것

사용자 정의 오류 메시지가 필요할 수도 있지만 그게 전부입니다. 다른 js 코드는 모두 삭제할 수 있습니다.

+0

내 대답이 업데이트되었습니다. 나는 당신의 코드에서 에러가 폼을 어떻게 찾는 지 정확히 말할 수는 없지만, 밸리 에이터 플러그인과 약간의 작업으로 이것이 당신에게 엄청난 양의 코드를 저장한다는 것을 알았다. 그리고 아약스 양식은 양식을 제출하는 과정을 단순화하므로 보낼 게시물/값을 수동으로 작성할 필요가 없습니다. –

+0

내 오류는 CSS 스타일이며 jquery 툴팁처럼 보입니다. 스타일을 적용하기 위해 특정 클래스가 첨부 된 다음 유효성 검사에 따라 표시되거나 숨겨집니다. 위에 포함 된 업데이트 된 코드를 사용하는 경우 "유효성 검사"파일을 첨부하거나 첨부해야합니까? – adamdehaven

+0

사용자 정의 유효성 검사가있는 경우 각각에 대해 유효성 검사기를 만들어야합니다. 위에있는 유효성 검사기를 실제로 사용하는 방식과 함께 사용할 수 있지만 약간의 작업을 수행해야합니다. 양식에 html이 어떻게 보이는지 원본 메시지에 포함시킬 수 있습니까? 나는 얼마나/오류가 나타나는 지 알기 힘듭니다. –

0

이것은 일반적으로 keyup 기능으로 달성됩니다. 키를 놓을 때마다 모든 필드가 정확한지 확인하기 위해 함수를 호출 할 수 있습니다. 그렇다면 사용자는 눈에 띄지 않게 알 수 있습니다. 귀하의 경우 모든 필드가 정확하지 않으면 제출 버튼이 비활성화 될 수 있습니다.

참고 :이 기능으로 현재 편집 텍스트 필드를 수정하지 않거나 사용자에게 불쾌감 것을 입증 할 것이다 다른 작업을 수행해서는 안)


편집 : 나는 모든 유효성을 검사하는 코드를 수정 모든 입력 필드에 대해 키가 해제 된 시간. JQuery에 익숙하지 않아서 바닐라 자바 ​​스크립트로 처리했습니다. 필요한 경우 변환이 매우 쉬워야합니다.

$(function(){ 


    var inputs = document.getElementsByTagName("input"); 

    for(var i = 0; i < inputs.length; i++) { 

    inputs[i].addEventListener("keyup", function(){validate()}, true); 

    } 


    $('.error').hide(); 
    $(".cool-button").click(function(){validate()}); 

    function validate() { 
          $('.error').hide(); 
          $("label#name_error").hide(); 
          $("label#invalid_error").hide(); 
          $("label#email_error").hide(); 
          $("label#invalid_phone_error").hide(); 
          $("label#phone_error").hide(); 
          $("label#zip_error").hide(); 

          var name=$("input#contact_name").val(); 
          var email=$("input#contact_email").val(); 
          var emailRegEx =/^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/ 
          var phone=$("input#contact_phone").val(); 
          var phone=phone.replace(/\s+-/g, ""); 
          var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/ 
          var zip=$("input#contact_zip").val(); 
          var best_time=$("input#contact_best_time").val(); 
          var message=$("textarea#contact_message").val(); 
          var timestamp=$("input#timestamp").val(); 

          if(name==""){ 
          $("label#name_error").show();$("input#contact_name").focus();return false; 
          } 
          if(email==""){ 
          $("label#email_error").show();$("input#contact_email").focus();return false; 
          } 
          if (document.getElementById('contact_email').value.search(emailRegEx)==-1) { 
          $("label#invalid_error").show();$("input#contact_email").focus();return false; 
          } 
          if(phone==""){ 
          $("label#phone_error").show();$("input#contact_phone").focus();return false; 
          } 
          if (document.getElementById('contact_phone').value.search(phoneRegEx)==-1) { 
          $("label#invalid_phone_error").show();$("input#contact_phone").focus();return false; 
          } 
          if(zip==""){ 
          $("label#zip_error").show();$("input#contact_zip").focus();return false; 
          } 
          if(message==""){ 
          $("label#message_error").show();$("textarea#contact_message").focus();return false; 
          } 
          else { 
          var dataString='contact_name='+name+'&contact_email='+email+'&contact_phone='+phone+'&contact_best_time='+best_time+'&contact_zip='+zip+'&timestamp='+timestamp+'&contact_message='+encodeURIComponent(message); 
          $.ajax({ 
           type:"POST", 
           url:"php/contact.php", 
           data:dataString, 
           success:function(){$('#contact-form').html("<div id='message'></div>");$('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at [email protected] or call us at 800-924-9473</p>").hide().fadeIn(800,function(){$('#message').append("<img id='checkmark' src='images/submit2.png' />");});}}); 
          } 
          return false; 
          }; 
    }); 
+0

이미 내가 이미 가지고있는 코드를 수정할 수있는 방법이 있습니까? 유효성 검사 메시지가 이미 내장되어 있으므로 사용자 정의 jQuery 툴팁이 있습니다. 입력 필드가 포커스를 잃었을 때 "else"문 앞에 모든 작업을 수행 한 다음 모든 필드가 유효한 경우에만 "else"작업을 수행하고 사용자가 제출 단추를 클릭 할 때만 수행하고 싶습니다. – adamdehaven

+0

추가 할 작업이나 코드가 많은 것처럼 보일 수 있지만 jquery 도구 유효성 검사기는 작은 플러그인이므로 양식을 제출할 때마다 위의 작업을 수행하는 경우 많은 양의 코드를 절약 할 수 있습니다. 양식 플러그인을 사용하면 수동으로 양식을 직렬화하지 않아도됩니다 (위에서도 수행 한 작업). –

+0

이 시점에서 사이트의 모든 양식을 다시 실행하려면 거대한 작업이 필요합니다. ( 함수를 두 개의 다른 것으로 나눕니다. 기능 1 - 입력 필드에서 흐림 또는 변경시 값을 가져온 다음 유효성을 검사하고 잘못된 경우 팝업 메시지를 표시합니다. 기능 2 - 첫 번째 기능이 설정되면 어떤 변수 (또는 그것을하는 더 좋은 방법)를 "유효"또는 무엇인가로 설정 한 다음 사용자가 제출 버튼을 클릭하면 양식이 제출됩니까? – adamdehaven

0

각 입력마다 유효성 검사를 중단하는 경향이 있습니다. 장기적으로 볼 때 더 모듈화 된 jQuery 플러그인을 사용할 수도 있습니다. 말했다

,이 같은 (working jsFiddle를) 그것을 할 것입니다 :

//contact form validation 
$(function() { 
    $('.error').hide(); //hide all errors 
    function fieldHasValue(field, label) { 
     var value = field.val().trim(); //Grab value without leading or trailing whitespace 
     if (value.length > 0) { 
      label.hide(); 
     } else { 
      label.show(); 
      field.focus(); 
     } 
     return (value.length > 0); 
    } 
    function nameIsValid() { 
     return fieldHasValue($("input#contact_name"), $("label#name_error")); 
    } 
    function emailIsValid() { 
     var email = $("input#contact_email").val().trim(); //Grab value without leading or trailing whitespace 
     var emailRegEx = /^([a-zA-Z0-9])(([a-zA-Z0-9])*([\._\-])?([a-zA-Z0-9]))*@(([a-zA-Z0-9\-])+(\.))+([a-zA-Z]{2,4})+$/; 
     var isValid = (email.length > 0) && email.match(emailRegEx); 
     if (isValid) { 
      $("label#email_error").hide(); 
      $("label#invalid_error").hide(); 
     } else if (email.length > 0) { 
      $("label#invalid_error").show(); 
      $("input#contact_email").focus(); 
     } else { 
      $("label#email_error").show(); 
      $("input#contact_email").focus(); 
     } 
     return isValid; 
    } 
    function phoneIsValid() { 
     var phone = $("input#contact_phone").val().replace(/\s+-/g, "").trim(); //Grab value without leading or trailing whitespace and replace [whitespace -] with an empty string. 
     var phoneRegEx = /^(1-?)?\s?(\([2-9]\d{2}\)|\s?-?[2-9]\d{2})-?\s?[2-9]\d{2}-?\d{4}$/; 
     var isValid = (phone.length > 0) && phone.match(phoneRegEx); 
     if (isValid) { 
      $("label#invalid_phone_error").hide(); 
      $("label#phone_error").hide(); 
     } else if (phone.length > 0) { 
      $("label#invalid_phone_error").show(); 
      $("input#contact_phone").focus(); 
     } else { 
      $("label#phone_error").show(); 
      $("input#contact_phone").focus(); 
     } 
     return isValid; 
    } 
    function zipIsValid() { 
     return fieldHasValue($("input#contact_zip"), $("label#zip_error")); 
    } 
    function messageIsValid() { 
     return fieldHasValue($("textarea#contact_message"), $("label#message_error")); 
    } 
    function bestTimeIsValid() { 
     return fieldHasValue($("input#contact_best_time"), $("label#best_time_error")); 
    } 
    function allInputsAreValid() { 
     var validName = nameIsValid(); 
     var validEmail = emailIsValid(); 
     var validPhone = phoneIsValid(); 
     var validZIP = zipIsValid(); 
     var validMessage = messageIsValid(); 
     var validBestTime = bestTimeIsValid(); 
     var isValid = validName && validEmail && validPhone && validZIP && validMessage && validBestTime; 
     return isValid; 
    } 
    $("input#contact_name").on('change blur', nameIsValid); 
    $("input#contact_email").on('change blur', emailIsValid); 
    $("input#contact_phone").on('change blur', phoneIsValid); 
    $("input#contact_zip").on('change blur', zipIsValid); 
    $("textarea#contact_message").on('change blur', messageIsValid); 
    $("input#contact_best_time").on('change blur', bestTimeIsValid); 
    $("input#contact_button").on('click', function (e) { 
     var timestamp = $("input#timestamp").val(); 

     if (allInputsAreValid()) { 
      var dataString = 'contact_name=' + name + '&contact_email=' + email + '&contact_phone=' + phone + '&contact_zip=' + zip + '&contact_best_time=' + best_time + '&timestamp=' + timestamp + '&contact_message=' + encodeURIComponent(message); 
      $.ajax({ 
       type: "POST", 
       url: "php/contact.php", 
       data: dataString, 
       success: function() { 
        $('#contact-form').html("<div id='message'></div>"); 
        $('#message').html("<h3>Message Sent</h3>").append("<p>Thank you for contacting us. We'll be in touch. <br /><br />If you have any further questions, you can always email us at [email protected] or call us at 800-924-9473</p>").hide().fadeIn(800, function() { 
         $('#message').append("<img id='checkmark' src='images/submit2.png' />"); 
        }); 
       } 
      }); 
     } 
     e.preventDefault(); 
     return false; 
    }); 
});