An example of the application of form validation plugin validation

Source: Internet
Author: User

Jquery. Validation is an excellent jquery plugin that validates client forms and provides a number of customizable properties and methods for good extensibility. Now combined with the actual situation, I have often used in the project validation organized into an example demo, this article is to explain this example to understand the application of validation.

The validation involved in this example is:

User name: Length, character verification, repetitive Ajax validation (if it already exists).

Password: Length verification, re-enter password verification.

Mail: Email address verification.

Landline: Fixed telephone number verification in mainland China.

Mobile number: Mobile phone number verification in mainland China.

URL: Site URL address verification.

Date: standard date format validation.

Number: integer, positive integer validation, numeric range validation.

Identity card: Mainland identification number verification.

Postal code: Mainland postcode verification.

File: File type (suffix) verification, such as only allow uploading of pictures.

IP:IP address Validation.

Verification Code: Verification Code AJAX authentication.

How to use:

1. Prepare jquery and Jquery.validate plugins

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

2. Prepare CSS Style

Page style I no longer detail, you can write a style, you can also see the demo page source code. The key style to emphasize here is to display the style of the validation information:

Label.error{color: #ea5200; margin-left:4px; padding:0px 20px  ; Background:url (Images/unchecked0  } label.right{margin-left:4px; padding-left:20px; Background:url (images/checked0

3. XHTML

<form id="MyForm"action="#"Method="Post"> <table width="100%"Border="0"cellspacing="0"cellpadding="0" class="mytable"> <trclass="Table_title"> &LT;TD colspan="2">jquery.validation form Validation </td> </tr> <tr> <td width="22%"align=" Right"> User name:</td> <td><input type="text"Name="User"Id="User" class="Input Required"/> <p> username is 3-16 characters, can be numeric, letter, underline, and Chinese </p></td> </tr> <tr> <td align=" Right"> Password:</td> <td><input type="Password"Name="Pass"Id="Pass" class="Input Required"/> <p> min. length:6Maximum length: -</p> </td> </tr> <tr> <td align=" Right"> Confirm Password:</td> <td><input type="Password"Name="Repass" class="Input Required"/></td> </tr> </table> </form>

Limited to space, this article only captures a small part of the HTML code in the instance, the detailed XHTML code can be see the page demo source code. It is worth mentioning that I am giving the label a "required" class style, which will be mentioned later in this article.

4. Application validation Plug-in

To invoke the validation plug-in method:

$ (function () {            var validate = $ ("#myform"). Validate ({          //            ......          },          //            ......          }     

Rules: Define validation rules, Key:value form, key is the element to be validated, value can be a string or an object. For example, verify the length of the user name and not allow null:

rules:{   user:{       required:true,       maxlength:+,       minlength:  3   },   

In fact, we can directly specify in the XHTML code the Class attribute of input to required, the function is not allowed to empty, so that in the JS section will not have to repeat the write. The same authentication email, etc., directly set the class attribute of input to email.

Messages: Defines the hint information, the form of Key:value key is the element to be validated, the value is a string or function, and the information is prompted when validation does not pass.

messages:{   user:{       required:" user name cannot be empty!"  ",       remote:" the user name already exists, please change a different user name! "   },   

In this case, the validation JS is written according to the above rules, the validation plug-in encapsulates a lot of basic authentication methods, as follows:

Required:true must have a value, cannot be empty

The Remote:url can be used to determine if the user name is already present, and the server-side output is true, indicating that validation passes

Minlength:6 Minimum length is 6

Maxlength:16 Maximum length is 16

Rangelength: Length Range

RANGE:[10,20] range of values between 10-20

Email:true Verifying messages

url:true Verifying URL URLs

Dateiso:true Verify date format ' Yyyy-mm-dd '

Digits:true only for Digital

Accept: ' gif|jpg ' only accepts images with a gif or JPG suffix. Extensions commonly used to validate files

Equalto: ' #pass ' is equal to the value of the form field, and is often used to verify a duplicate password

In addition, I also based on the actual situation of the project to expand a few validation, validation of the code in Validate-ex.js, before use need to load this JS. It can provide the following validation:

Username:true user name can only include Chinese characters, English letters, numbers, and underscores

Ismobile:true Mobile phone Number verification

Isphone:true Mainland Mobile phone number verification

Iszipcode:true Post Code verification

Isidcardno:true Mainland ID Number verification

Ip:true IP Address Verification

The verification methods provided above basically meet our needs in most projects. If other special validation requirements can be extended, methods such as:

JQuery.validator.addMethod ("iszipcode", function (value, Element) {         var zip =/^[0-9]{6}$/;        return this. Optional (element) | | (Zip.test (value));      " please fill in your zip code correctly! "
Troubleshooting Problem Solving

1, encountered in the project when verifying the existence of the user name, found that the Chinese input validation is not supported. My solution is to give the user name encodeURIComponent encoding, background PHP and then the accepted value of UrlDecode decoding

user:{     Remote: {           "chk_user.php"//         " Post " //           data: {user:function () {               return encodeuricomponent ($ (" #user " //          }}      }  

The code for the server-side validator chk_user.php:

<?PHP $request= UrlDecode (Trim ($_post['User'])); Usleep (150000); $users= Array ('Moonlight Light','Jeymii','Peter','Helloweba'); $valid='true'; foreach($users as$user) {     if(Strtolower ($user) = =$request) $valid='false'; } Echo $valid; ?>

I use the server program is PHP, you can also use Asp,asp.net,java and so on. In addition, in order to demonstrate that the user name data is directly written on the server, the real application is to retrieve the user name data from the database to compare with the receiving client's data.

2. When validating the checkbox and the radio control, the validation information does not appear behind the last control text, but directly behind the first control and does not meet our requirements.

The workaround is to append the following code to 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 ()); ElseError.insertafter (element);} 

3. Reset the form. The original reset method of form form is reset comes with

<input type=" reset" value="   Reset"

Click the "Reset" button, the form element will be reset, but after running the validation plug-in, the verification message is not reset, that is, those messages did not disappear. Thank validation for providing a way to reset the form: Resetform ()

$ ("input:reset"). Click (function () {     
Other

1, this example also involves the verification code of the Judgment method, is also through the asynchronous generation of verification code and determine whether the input is correct, you can view the source code, the official network provides an example: http://jquery.bassistance.de/validate/demo/captcha/

2. More application of verification method see http://jqueryvalidation.org/

An example of the application of form validation plugin validation

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.