Examples of the Form Verification plug-in Validation Application

Source: Internet
Author: User

Examples of the Form Verification plug-in Validation Application

Jquery. Validation is an excellent jquery plug-in that can verify the client form and provides many customizable attributes and methods for good scalability. Now, based on the actual situation, I organize the verification frequently used in the project into an instance DEMO. This article explains this instance to understand the application of Validation.

Verification involved in this instance includes:
Username: length, character verification, and repeated ajax verification (whether the user exists ).
Password: length verification. Repeat the password verification.
Email: Verify the email address.
Landline phone: Chinese mainland landline phone number verification.
Mobile phone number: Mainland China Mobile Phone number verification.
URL: Verify the website URL.
Date: Standard Date Format verification.
Number: integer, positive integer verification, number range verification.
ID card: Chinese mainland ID card number verification.
Zip code: Mainland China zip code verification.
File: file type (suffix) verification. For example, only images can be uploaded.
IP Address: Verify the IP address.
Verification Code: ajax verification code.
Usage:
1. Prepare the jquery and jquery. validate plug-ins.

<script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.validate.js"></script> 

2. Prepare CSS styles
I will not elaborate on the page style. You can write a style yourself or refer to the DEMO page source code. The key style to be emphasized here is to display the style of verification information:

label.error{color:#ea5200; margin-left:4px; padding:0px 20px; background:url(images/unchecked.gif) no-repeat 2px 0 } label.right{margin-left:4px; padding-left:20px; background: url(images/checked.gif) no-repeat 2px 0} 

3. XHTML

<Form id = "myform" action = "#" method = "post"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = "0" class = "mytable"> <tr class = "table_title"> <td colspan = "2"> jquery. verify the validation form </td> </tr> <td width = "22%" align = "right"> User Name: </td> <input type = "text" name = "user" id = "user" class = "input required"/> <p> the user name must be 3-16 characters long, it can be numbers, letters, underscores, and Chinese characters </p> </td> </tr> <td align = "right"> password: </td> <input type = "password" name = "pass" id = "pass" class = "input required"/> <p> minimum length: 6 max length: 16 </p> </td> </tr> <td align = "right"> Confirm Password: </td> <input type = "password" name = "repass" class = "input required"/> </td> </tr> </table> </form>

It is worth mentioning that I have given the label a "required" style, which will be described below.
4. Application Validation plug-in
Method for calling the Validation plug-in:

$ (Function () {var validate = $ ("# myform "). validate ({rules: {// define verification rules ......}, messages: {// define the prompt message ......}})});

Rules: defines verification rules, in the form of key: value. key is the element to be verified, and value can be a string or object. For example, the length of the verified user name and the value cannot be blank:

rules:{  user:{    required:true,    maxlength:16,    minlength:3  },  ...... } 

In fact, in XHTML code, we can directly specify the class attribute of input as required, so that it is not allowed to be empty, so that the JS part does not need to be repeated. For the same verification email, directly set the class attribute of input to email.
Messages: defines the prompt information. In the form of key: value, the key is the element to be verified, and the value is a string or function. The prompt information is displayed when the verification fails.

Messages: {user: {required: "The user name cannot be blank! ", Remote:" This user name already exists. Please change to another user name! "},......}

In this example, the verification JS is compiled according to the above rules. The Validation plug-in encapsulates many basic verification methods, as shown below:
Required: true must have a value and cannot be blank
Remote: the url can be used to determine whether the user name or so already exists. The server outputs true, indicating that the verification has passed
Minlength: 6 the minimum length is 6
Maxlength: 16 max length: 16
Rangelength: length range
Range: [10, 20] The value range is between 10 and 20.
Email: true verification email
Url: true
DateISO: true verification Date Format 'yyyy-mm-dd'
Digits: true can only be a number
Accept: 'gif | jpg 'only accepts gif or jpg images with the suffix. Used to verify the file extension
Similar to: '# pass' and which form field has the same value. It is often used to verify repeated passwords.
In addition, I also extended several verifications according to the actual situation of the project, the verification code is in the validate-ex.js and needs to load this JS first before use. It provides the following verification:
UserName: true the user name can only contain Chinese characters, English letters, numbers, and underscores
IsMobile: true mobile phone number verification
IsPhone: true Chinese mobile phone number verification
IsZipCode: true zip code verification
IsIdCardNo: true mainland ID card number verification
Ip: true ip address verification
The verification methods provided above basically meet our needs in most projects. If you have other special verification requirements, you can extend them by using the following methods:

JQuery. validator. addMethod ("isZipCode", function (value, element) {var zip =/^ [0-9] {6} $/; return this. optional (element) | (zip. test (value) ;}, "Please enter your zip code correctly! ");

Troubleshooting:
1. If a user name is verified in a project, Chinese input verification is not supported. My solution is to encode the username with encodeURIComponent, And the backend PHP then decodes the accepted value with urldecode.

User: {remote: {url: "chk_user.php", // server verification program type: "post", // submission method data: {user: function () {return encodeURIComponent ($ ("# user "). val (); // encoded data }}}},

Code of the chk_user.php server verification program:

<? Php $ request = urldecode (trim ($ _ POST ['user']); usleep (150000); $ users = array ('zhuguang', 'jeymii ', 'Peter ', 'hellowebba'); $ valid = 'true'; foreach ($ users as $ user) {if (strtolower ($ user) = $ request) $ valid = 'false';} echo $ valid;?>

My server program is PHP. You can also use ASP, ASP. NET, JAVA, and so on. In addition, in this example, the user name data is directly written on the server, and the real application extracts the user name data from the database to compare the data of the receiving client.
2. When verifying the checkbox and radio controls, the verification information does not appear behind the last control text, but directly follows the first control and does not meet our requirements.

The solution is to append the following code in validate:

errorPlacement: function(error, element) {   if ( element.is(":radio") )     error.appendTo ( element.parent() );   else if ( element.is(":checkbox") )     error.appendTo ( element.parent() );   else if ( element.is("input[name=captcha]") )     error.appendTo ( element.parent() );   else     error.insertAfter(element); } 

3. Reset the form. The original reset method of Form is reset.

<Input type = "reset" value = "reset"/>

Click "reset", and the form element will be reset. However, after the Validation plug-in is run, the verification prompt information is not reset, that is, the prompt information does not disappear. Thanks to Validation for providing the method to reset the form: resetForm ()

$("input:reset").click(function(){   validate.resetForm(); }); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.