When developing a system, there are often certain form data that are required. If jQuery is used to verify through ID, it will not only affect efficiency, but also cause omissions, making it difficult to maintain later.
This chapter will introduce how to use jQuery to perform unified verification by configuring classes for forms. (ID can only be used once on a page; class can be referenced multiple times)
1: Add a class to the input. The name can be set at will, but each input needs to be consistent. In this chapter, calss is set to noNull. (If the input already has a class attribute, it can be added directly after it)
2: Add an attribute to the input to obtain the field through jquery later and use it as a prompt. The case prompt attribute in this chapter is notNull.
3: Use jQuery to traverse all forms with calss noNull in the page and verify whether it is empty. If it is empty, obtain the notNull field and provide an empty prompt.
For details on how to set it up, please refer to the case below. This chapter explains input, radio, select, checkbox and other types.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> </head> <body> <form> <!-- input --> <div> 姓名: <input type="text" name="name" notNull="姓名" class="form-control noNull"> </div> <br> <!-- radio --> <div> 性别: 男<input type="radio" name="sex" value="0" class="noNull" notNull="性别"> 女<input type="radio" name="sex" value="1" > </div> <br> <!-- select --> <div> 年龄: <select name="age" class="noNull" notNull="年龄"> <option value ="">请选择</option> <option value ="1">1</option> <option value ="2">2</option> </select> </div> <br> <!-- checkbox --> <div> 兴趣: 打球<input type="checkbox" name="hobby" value="1" class="noNull" notNull="兴趣"> 唱歌<input type="checkbox" name="hobby" value="2"> 跳舞<input type="checkbox" name="hobby" value="3"> </div> <br> <button type="button" class="btn-c" onclick="bubmi()">保存</button> </form> <script src="jquery-1.9.1.min.js"></script> <script type="text/javascript"> function bubmi(){ $(".noNull").each(function(){ var name = $(this).attr("name"); if($(this).val()==""){ alert($(this).attr('notNull')+"不能为空");return false; } if($(this).attr("type")=="radio"){ if ($("input[name='"+name+"']:checked").size() < 1){ alert($(this).attr('notNull')+"不能为空!"); return false; } } if($(this).attr("type")=="checkbox"){ if ($('input[name="'+name+'"]:checked').size() < 1){ alert($(this).attr('notNull')+"不能为空!"); return false; } } }) } </script> </body> </html>
The following introduces you to the jquery.validate.js verification plug-in
jquery.validate.js is a verification plug-in under jquery. With the advantages of jquery, we can quickly verify some common inputs and expand our own verification methods.
For example, there is such a form:
<form id="signupForm" method="get" action=""> <fieldset> <legend>Validating a complete form</legend> <p> <label for="firstname">Firstname</label> <input id="firstname" name="firstname" class="required"/> </p> <p> <label for="lastname">Lastname</label> <input id="lastname" name="lastname" /> </p> <p> <label for="username">Username</label> <input id="username" name="username" /> </p> <p> <label for="password">Password</label> <input id="password" name="password" type="password" /> </p> <p> <label for="confirm_password">Confirm password</label> <input id="confirm_password" name="confirm_password" type="password" /> </p> <p> <label for="email">Email</label> <input id="email" name="email" /> </p> <p> <input class="submit" type="submit" value="Submit"/> </p> </fieldset> </form>
In this form, there are first name, last name, username, password, confirm password and email. They all need to be non-empty, and the email needs to be a properly formatted address, the confirm password and the password consistent. The simplest way to use jQuery validation is to introduce two js files, jquery.js and jquery validation.js. Then add class to the input respectively:
<input id="firstname" name="firstname" class="required"/> <input id="lastname" name="lastname" class="required"/> <input id="username" name="username" class="required"/> <input id="password" name="password" type="password" class="required"/> <input id="confirm_password" name="confirm_password" type="password" class="required" equalTo="#password"/> <input id="email" name="email" class="required email"/>
The following lists the default verifications that come with validate
required: "Required field",
remote: "Please correct this field",
email: "Please enter the correct format of your email",
url: "Please enter a legal URL",
date: "Please enter a legal date",
dateISO: "Please enter a valid date (ISO).",
number: "Please enter a legal number",
digits: "Only integers can be entered",
creditcard: "Please enter a valid credit card number",
equalTo: "Please enter the same value again",
accept: "Please enter a string with a legal suffix",
maxlength: jQuery.format("Please enter a string with a length of at most {0}"),
minlength: jQuery.format("Please enter a string with a length of at least {0}"),
rangelength: jQuery.format("Please enter a string with a length between {0} and {1}"),
range: jQuery.format("Please enter a value between {0} and {1}"),
max: jQuery.format("Please enter a value up to {0}"),
min: jQuery.format("Please enter a minimum value of {0}")
Then, in the read event of the document, add the following method:
<script> $(document).ready(function(){ $("#signupForm").validate(); } </script>
In this way, when the form is submitted, it will be verified based on the class specified by the input. If it fails, submission of the form will be blocked. And, the prompt information is displayed behind the input.
However, this feels bad because the validation rules invade our html code. Another way is to use "rules". We delete the verification classes for input. Then modify the document’s ready event response code:
$(document).ready(function(){ $("#signupForm").validate({ rules:{ firstname:"required", lastname:"required", username:"required", password:"required", confirm_password:{ required:true, equalTo:"#password" }, email:{ required:true, email:true } } }); })
In this way, the same effect can be achieved.
Then, the next question is that the error message displayed is the default. We need to use a custom prompt:
$(document).ready(function(){ $("#signupForm").validate({ rules:{ firstname:"required", lastname:"required", username:"required", password:"required", confirm_password:{ required:true, equalTo:"#password" }, email:{ required:true, email:true } }, messages:{ firstname:"必填项", lastname:"必填项", username:"必填项", password:"必填项", confirm_password:{ required:"必填项", equalTo:"密码不一致" }, email:{ required:"必填项", email:"格式有误" } } }); })
If you also want to display a special style on the error message (for example, the font is red), you can add:
<style type="text/css"> #signupForm label.error { padding-left: 16px; margin-left: 2px; color:red; background: url(img/unchecked.gif) no-repeat 0px 0px; } </style>
Continue to add validation rules for the input password length:
$(document).ready(function(){ $("#signupForm").validate({ rules:{ firstname:"required", lastname:"required", username:"required", password:{ required:true, minlength:4, maxlength:15 }, confirm_password:{ required:true, equalTo:"#password" }, email:{ required:true, email:true } }, messages:{ firstname:"必填项", lastname:"必填项", username:"必填项", password:{ required:"必填项", minlength:jQuery.format("密码长度不少于{0}位"), maxlength:jQuery.format("密码长度不超过{0}位") }, confirm_password:{ required:"必填项", equalTo:"密码不一致" }, email:{ required:"必填项", email:"格式有误" } } }); })
Use remote
You can specify the triggering effect method through event (optional values include keyup (every time a key is pressed), blur (when the control loses focus), if not specified, it will only trigger when the submit button is pressed)
$(document).ready(function(){ $("#signupForm").validate({ event:"keyup" || "blur" }) })
If you specify debug as true, the form will not be submitted and can only be used for verification (default is submission) and can be used for debugging
$(document).ready(function(){ $("#signupForm").validate({ debug:true }) })
If you need to perform some custom processing before submitting, use the submitHandler parameter
$(document).ready(function(){ $("#signupForm").validate({ SubmitHandler:function(){ alert("success"); } }) })