jquery validation plug-in form validation instance

Source: Internet
Author: User
Tags php code prepare valid email address

The validation that is involved in this example is:

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

Password: Length verification, repeat input password verification.

Mail: Email address verification.

Fixed Telephone: Fixed telephone number verification in mainland China.

Mobile phone Number: China mainland mobile phone number verification.

Web address: Site URL verification.

Date: standard date format validation.

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

ID Card: Mainland ID card number verification.

Zip Code: Mainland ZIP code verification.

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

IP:IP address verification.

Verification Code: Verification Code AJAX verification.

SEP17 examples explain the application of the form verification plug-in validation helloweba.com Author: Moonlight Light time:2010-09-17 11:41 the jquery plug-in form validation
Jquery. Validation is an excellent jquery plug-in that validates client forms and provides a number of customizable properties and methods for good scalability. In the past several projects, I have used the validation, now combined with the actual situation, I will often use the validation of the project to organize into an example demo, this article is to explain this example to understand the application of validation.


The validation that is involved in this example is:

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

Password: Length verification, repeat input password verification.

Mail: Email address verification.

Fixed Telephone: Fixed telephone number verification in mainland China.

Mobile phone Number: China mainland mobile phone number verification.

Web address: Site URL verification.

Date: standard date format validation.

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

ID Card: Mainland ID card number verification.

Zip Code: Mainland ZIP code verification.

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

IP:IP address verification.

Verification Code: Verification Code AJAX verification.

Sep

17

Example to explain the application of form verification plug-in validation

Helloweba.com Author: Moonlight light time:2010-09-17 11:41 tag:validation jquery plug-in form validation

Jquery. Validation is an excellent jquery plug-in that validates client forms and provides a number of customizable properties and methods for good scalability. In the past several projects, I have used the validation, now combined with the actual situation, I will often use the validation of the project to organize into an example demo, this article is to explain this example to understand the application of validation.

The validation that is involved in this example is:

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

Password: Length verification, repeat input password verification.

Mail: Email address verification.

Fixed Telephone: Fixed telephone number verification in mainland China.

Mobile phone Number: China mainland mobile phone number verification.

Web address: Site URL verification.

Date: standard date format validation.

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

ID Card: Mainland ID card number verification.

Zip Code: Mainland ZIP code verification.

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

IP:IP address verification.

Verification Code: Verification Code AJAX verification.

How to use:

1. Prepare jquery and Jquery.validate Plug-ins

The code is as follows Copy Code

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

2. Prepare CSS Style

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

The code is as follows Copy Code

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

The code is as follows Copy Code

&lt;form id= "MyForm" action= "#" method= "POST" &gt;


&lt;table width= "100%" border= "0" cellspacing= "0" cellpadding= "0" class= "mytable" &gt;


&lt;tr class= "Table_title" &gt;


&LT;TD colspan= "2" &gt;jquery.validation form verification &lt;/td&gt;


&lt;/tr&gt;


&lt;tr&gt;


&LT;TD width= "22%" align= "right" &gt; Username:&lt;/td&gt;


&lt;td&gt;&lt;input type= "text" name= "user" id= "user" class= "input required"/&gt;


&lt;p&gt; user name is 3-16 characters, can be numbers, letters, underscores, and Chinese &lt;/p&gt;&lt;/td&gt;


&lt;/tr&gt;


&lt;tr&gt;


&LT;TD align= "Right" &gt; Password:&lt;/td&gt;


&lt;td&gt;&lt;input type= "password" name= "pass" id= "pass" class= "input required"/&gt;


&lt;p&gt; min Length: 6 Maximum length:16&lt;/p&gt;


&lt;/td&gt;


&lt;/tr&gt;


&lt;tr&gt;


&LT;TD align= "Right" &gt; Confirm password:&lt;/td&gt;


&lt;td&gt;&lt;input type= "Password" name= "repass" class= "input Required"/&gt;&lt;/td&gt;


&lt;/tr&gt;


&lt;/table&gt;


&lt;/form&gt;

Limited to space, this article only intercepts 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 gave the label a "required" class style, and the following will refer to its role.

4, the application of validation plug-ins

How to invoke the validation plug-in:

  code is as follows copy code

$ (function () {        
     var validate = $ ("#myform"). Validate ({ 
          rules:{ //define validation rules  
         &NBSP;&NBSP;&NBSP;&NBSP;......&NBSP
         }, 
         messages:{ //defines the hint information  
             ...... 
       &NBSP;&NBSP;&NBSP;}&NBSP
    })  
}  

Rules: Defines a validation rule, in the form of Key:value, where the key is the element to be validated, and value can be a string or object. For example, verify the length of the username and not allow null:

The code is as follows Copy Code

rules:{
user:{
Required:true,
Maxlength:16,
Minlength:3
},
......
}

In fact, we in the XHTML code can directly specify the input class attribute to required, the role is not allowed to empty, so in the JS section does not have to repeat the writing. The same authentication email, set the input class attribute directly to email.

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

The code is as follows Copy Code

messages:{
user:{
Required: "User name cannot be empty!" ",
Remote: "This username already exists, please change another username!" "
},
......
}

In this case, the validation JS is written in accordance with the rules above, validation plug-ins encapsulate a lot of basic authentication methods, as follows:

Required:true must have a value and cannot be empty

Remote:url can be used to determine whether a 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] Value range is between 10-20

Email:true Authentication Message

Url:true Authentication URL URLs

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

Digits:true can only be a number

Accept: ' gif|jpg ' only accepts pictures of GIF or JPG suffixes. Extensions that are commonly used to verify files

Equalto: ' #pass ' is equal to the value of the form field, which is often used to validate the repeated input password

In addition, I also based on the actual situation of the project to extend a few verification, validated code in Validate-ex.js, before using the 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 ZIP Code Verification

Isidcardno:true Mainland ID Card number verification

Ip:true IP Address Verification

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

The code is as follows Copy Code

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");

Difficult Problem solving

1, in the project encountered in the verification of the existence of the user name, the discovery does not support Chinese input validation. My solution is to encodeuricomponent the user name code, backstage PHP to accept the value of the UrlDecode decoding

  code is as follows copy code

user:{ 
    remote: {  
         url:  "chk_user.php",  //server-side validator  
          type:  "POST",  //submit way  
          data: { user: function ()  {  
              return encodeuricomponent ($ ("#user"). Val ());  //encoded data  
         }}  
  &NBSP;&NBSP;&NBSP;}&NBSP;&NBSP
}, 

Server-Side Validator chk_user.php code:

The code is as follows Copy Code

<?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-side program is PHP, you can also use Asp,asp.net,java and so on. In addition, in order to demonstrate, the user name data is written directly on the service side, the real application is from the database out of the user name data, and to receive the client data comparison.

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

The workaround is to append the following code to validate ({}):

The code is as follows Copy Code

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. Form form The original reset method is reset self belt

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

When you click the "Reset" button, the form elements will be reset, but after you run the validation plug-in, the validation message is not reset, and that message is not gone. Thank validation for providing a way to reset a form: Resetform ()

The code is as follows Copy Code

$ ("Input:reset"). Click (function () {
Validate.resetform ();
});

The following example is my own use of sharing to everyone

The code is as follows Copy Code



/**//**


* @author Ming


*/


$ (document). Ready (function () {





/**//* Set Default Properties *


$.validator.setdefaults ({


Submithandler:function (form) {


Form.submit ();


}


});





Character validation


JQuery.validator.addMethod ("Stringcheck", function (value, Element) {


return this.optional (Element) | | /^[u0391-uffe5w]+$/.test (value);


"Can only include Chinese characters, English letters, numbers and underscores");





Two bytes in text


JQuery.validator.addMethod ("Byterangelength", function (value, element, param) {


var length = Value.length;


for (var i = 0; i &lt; value.length; i++) {


if (Value.charcodeat (i) &gt; 127) {


length++;


}


}


return this.optional (Element) | | (length &gt;= param[0] &amp;&amp; length &lt;= param[1]);


"Make sure that the value entered is between 3-15 bytes (2 bytes in one)");





ID Card number Verification


JQuery.validator.addMethod ("Isidcardno", function (value, Element) {


return this.optional (Element) | | Isidcardno (value);


"Please enter your ID number correctly");





Mobile phone number Verification


JQuery.validator.addMethod ("IsMobile", function (value, Element) {


var length = Value.length;


var mobile =/^ ((13[0-9]{1}) | ( 15[0-9]{1})) +d{8}) $/;


return this.optional (Element) | | (length = = &amp;&amp; Mobile.test (value));


"Please fill in your mobile phone number correctly";





Phone number Verification


JQuery.validator.addMethod ("Istel", function (value, Element) {


var tel =/^d{3,4}-?d{7,9}$/; Phone number format 010-12345678


return this.optional (Element) | | (Tel.test (value));


"Please fill in your phone number correctly");





Contact Phone (cell phone/Phone can be) verified


JQuery.validator.addMethod ("Isphone", function (value,element) {


var length = Value.length;


var mobile =/^ ((13[0-9]{1}) | ( 15[0-9]{1})) +d{8}) $/;


var tel =/^d{3,4}-?d{7,9}$/;


return this.optional (Element) | | (tel.test (value) | | mobile.test (value));





"Please fill in your contact number correctly";





ZIP Code Verification


JQuery.validator.addMethod ("Iszipcode", function (value, Element) {


var tel =/^[0-9]{6}$/;


return this.optional (Element) | | (Tel.test (value));


"Please fill in your zip code correctly");





Start validation


$ (' #submitForm '). Validate ({


/**//* set up validation rules * *


Rules: {


Username: {


Required:true,


Stringcheck:true,


BYTERANGELENGTH:[3,15]


},


email:{


Required:true,


Email:true


},


phone:{


Required:true,


Isphone:true


},


address:{


Required:true,


Stringcheck:true,


BYTERANGELENGTH:[3,100]


}


},





/**//* SET Error message * *


Messages: {


Username: {


Required: "Please fill in User name",


Stringcheck: "User name can only include Chinese characters, English letters, numbers and underscores",


Byterangelength: "Username must be between 3-15 characters (2 characters in one)"


},


email:{


Required: "Please enter an email address",


Email: "Please enter a valid email address"


},


phone:{


Required: "Please enter your contact number",


Isphone: "Please enter a valid contact number"


},


address:{


Required: "Please enter your contact address",


Stringcheck: "Please enter your contact address correctly",


Byterangelength: Please detail your contact address for us to contact you.


}


},





/**//* Set Validation Trigger event * *


Focusinvalid:false,


Onkeyup:false,





/**//* set error message to prompt DOM */


Errorplacement:function (Error, Element) {


Error.appendto (Element.parent ());


},





});





});

Test Page index.html

The code is as follows Copy Code

&lt;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"


"Http://www.w3.org/TR/html4/loose.dtd" &gt;


&lt;html xmlns= "http://www.w3.org/1999/xhtml" &gt;


&lt;head&gt;


&lt;meta http-equiv= "Content-type" content= "text/html; CHARSET=GBK "/&gt;


&lt;title&gt;jquery Verification &lt;/title&gt;


&lt;script src= "Lib/jquery/jquery-1.3.2.min.js" &gt;&lt;/script&gt;


&lt;script type= "Text/javascript" src= "Lib/jquery/jquery.validate.js" mce_src= "Lib/jquery/jquery.validate.js" &gt; &lt;/script&gt;


&lt;script type= "Text/javascript" src= "Lib/jquery/messages_cn.js" &gt;&lt;/script&gt;


&lt;script type= "Text/javascript" src= "Lib/jquery/formvalidatorclass.js" &gt;&lt;/script&gt;


&lt;style type= "Text/css" &gt;

* {}{


Font-family:verdana;


font-size:96%;


}


Label {} {


Width:10em;


Float:left;


}


Label.error {} {


Float:none;


color:red;


Padding-left:. 5em;


Vertical-align:top;


}


P {} {


Clear:both;


}


. Submit {} {


Margin-left:12em;


}


Em {} {


Font-weight:bold;


Padding-right:1em;


Vertical-align:top;


}





&lt;/style&gt;


&lt;/head&gt;


&lt;body&gt;


&lt;form class= "SubmitForm" id= "SubmitForm" method= "Get" action= "" &gt;


&lt;fieldset&gt;


&lt;legend&gt; Form Validation &lt;/legend&gt;


&lt;p&gt;


&lt;label for= "username" &gt; Username &lt;/label&gt;


&lt;em&gt;*&lt;/em&gt;&lt;input id= "UserName" name= "UserName" size= "


&lt;/p&gt;


&lt;p&gt;


&lt;label for= "Email" &gt;E-Mail&lt;/label&gt;


&lt;em&gt;*&lt;/em&gt;&lt;input id= "Email" name= "email" size= "/&gt;"


&lt;/p&gt;


&lt;p&gt;


&lt;label for= "Phone" &gt; Tel &lt;/label&gt;


&lt;em&gt;*&lt;/em&gt;&lt;input id= "Phone" name= "Phone" size= "value=" "/&gt;"


&lt;/p&gt;


&lt;p&gt;


&lt;label for= "Address" &gt; Addr &lt;/label&gt;


&lt;em&gt;*&lt;/em&gt;&lt;input id= "Address" name= "Address" size= "&gt;"


&lt;/p&gt;


&lt;input class= "Submit" type= "Submission" value= "submitted"/&gt;


&lt;/p&gt;


&lt;/fieldset&gt;


&lt;/form&gt;


&lt;/body&gt;


&lt;/html&gt;

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.