如何执行提交表单验证

时间:2016-01-20 16:37:01

标签: javascript jquery forms validation

我想用表格字段失去焦点时执行的动态完整性和正确性检查替换表单中的提交后检查。

我该怎么做?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
  <head>
    <title>Form</title>
    <style>
body {    
  width: 500px;
}
.part {
  width: 100%;
  padding: 5px;
  border-bottom: 1px solid #000;
}
label {
  margin-right: 5px;
}
.label-left {
  text-align: right;
}
.label-right {
  text-align: left;
}
.error {
  color: #cc0000;
}
    </style>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
      //$(document).ready(function() {

	function myValidateEMailAddress(email_address) {
     
     var email_pattern = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
     return email_pattern.test(email_address);
  }
  
  function checkPassword(pwd_str) {
   var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
   return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
     
     var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
     return phone_pattern.test(phone_number);
  }

  $(document).ready(function() {    
    $('#form').submit(function(e) {
      var my_errors = false;
      $('.part> .error').remove();
      $('#my_submission').empty();
      $(':text, :password, textarea').each(function() {
        $(this).val($.trim($(this).val()));
        if ($(this).val() == '') {
           $(this).parent().append('<div class="error">Please provide a value</div>');
           my_errors = true;
        }
      });
      if ($('#email').val() != '') {
         if (!myValidateEMailAddress($('#email').val())) {
            $('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
            my_errors = true;
         }
      }
	  if ($('#your_password').val() != '') {
         if (!checkPassword($('#your_password').val())) {
            $('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
            my_errors = true;
         }
      }
	   if ($('#phone').val() != '') {
         if (!validatePhoneNumber($('#phone').val())) {
            $('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
            my_errors = true;
         }
      }
      if ($('#addresses option:selected').val() == '') {
         $('#addresses').parent().append('<div class="error">Please select one item</div>');
         my_errors = true;
      }
	  if ($(':radio[name="sex"]:checked').length == 0) {
         $(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
         my_errors = true;
      }
	  if ($(':radio[name="subscription"]:checked').length == 0) {
         $(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
         my_errors = true;
      }
      if ($('#likes option:selected').val() == '') {
         $('#likes').parent().append('<div class="error">Please select one item</div>');
         my_errors = true;
      }
      if (my_errors) {
         return false;
      }
      else {
         e.preventDefault();
         var my_submission_array = $('#form').serialize().split('&');
         if (my_submission_array.length > 0) {
            $('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
            for (var i = 0; i < my_submission_array.length; i++) {
                var my_pair = my_submission_array[i].split('=');
                $('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
            }
         }
      }
    });
  });

     // });
    </script>  
  </head>
  <body>
    <h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
 <div class="part">
    <label for="addresses" class="label-left">How should you be addressed?</label>
    <select name="addresses" id="addresses">
      <option value="">Please select one</option>
      <option value="first">Mr.</option>
      <option value="second">Madam</option>
      <option value="third">Miss</option>
      <option value="fourth">Dr.</option>
	  <option value="fifth">Pr.</option>
    </select>	  
  </div>
 
  <div class="part">
    <fieldset>
      <legend>Sex:</legend>
      <input type="radio" name="sex" id="group1" value="1">
      <label for="group1" class="label-right">Male</label> 
      <input type="radio" name="sex" id="group2" value="2">
      <label for="group2" class="label-right">Female</label>
    </fieldset>
  </div>
  <div class="part">
    <label for="last_name" class="label-left">Last Name: </label>
    <input type="text" name="last_name" id="last_name">
  </div>
  <div class="part">
    <label for="first_name" class="label-left">First Name: </label>
    <input type="text" name="first_name" id="first_name">
  </div>
  <div class="part">
    <label for="email" class="label-left">E-Mail: </label>
    <input type="text" name="email" id="email">
  </div>
  <div class="part">	
		<label for="your_password">Password:</label>
		<input type="password" name="your_password" id="your_password" size="10" maxlength="20">	
	</div>
	<div class="part">
    <label for="phone" class="label-left">Phone number: </label>
    <input type="text" name="phone" id="phone">
  </div>
  <div class="part">
    <label for="likes" class="label-left">What are your likes?</label>
    <select name="likes" id="likes">
      <option value="">Please select one</option>
      <option value="first">Programming</option>
      <option value="second"> African literature</option>
      <option value="third">Poetry</option>
      <option value="four">Dancing</option>
    </select>	  
  </div>
  <div class="part">
    <fieldset>
      <legend>Do you want to receive our newsletter ?</legend>
      <input type="radio" name="subscription" id="group1" value="1">
      <label for="group1" class="label-right">Yes</label> 
      <input type="radio" name="letter" id="group2" value="2">
      <label for="group2" class="label-right">No</label>
    </fieldset>
  </div>
  <div class="part">
    <label for="comments" class="label-left">Write some comments below:</label>
    <textarea name="comments" id="comments" cols="40" rows="3"></textarea>
  </div>
  <div class="part">
    <input type="submit" name="submit" id="submit" value="Submit Form">
  </div>
  <div id="my_submission"></div>
</form>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

在我继续回答之前,我应该注意到你在<html>标记之前放了jQuery脚本。这是不正确的。它必须在<head>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
  当表单字段失去焦点时执行

单击远离它时,元素会失去焦点。 jQuery发生了这个场合的blur事件:

$('input').on('blur', function() {
    // your code here
});

所以你可能想这样做:

$('#email').on('blur', function() {
    var emailVal = $(this).val();
    if (!emailVal || !myValidateEMailAddress(emailVal)) {
        $(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
        my_errors = true;
    }
});

其余代码看起来可能类似。