Jquery.validate Custom verification method and validate correlation parameter _jquery

Source: Internet
Author: User
Tags commit wrapper

Jquery Validate Related parameters

Define Chinese message
var cnmsg = {
Required: "Required fields",
remote: "Please correct this field",
email: "Please enter the correct format email",
URL: "Please enter a valid URL" , date
: "Please enter a valid date",
dateiso: "Please enter a valid date (ISO).",
Number: "Please enter the valid numbers",
digits: "Only integer",
CreditCard: "Please enter a valid credit card number",
equalto: "Please enter the same value again",
Accept: "Please enter a string with a valid suffix name",
Maxlength:jQuery.format ( "Please enter a string of up to {0}"),
Minlength:jQuery.format ("Please enter a string with a length of at least {0}"),
Rangelength:jQuery.format (" Please enter a string "between {0} and {1}",
Range:jQuery.format ("Enter a value between {0} and {1}"),
Max:jQuery.format ("Please enter a maximum of {0}"). Value "),
Min:jQuery.format (" Enter a value of min {0} ")
};
Jquery.extend (JQuery.validator.messages, cnmsg);

Validate Custom Validation

$ (document). Ready (function () {/** * ID number Verification */function Isidcardno (num) {var factorarr = new Array (7,9,10,5,8,4,2,1,
6,3,7,9,10,5,8,4,2,1);
var paritybit=new Array ("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2");
var vararray = new Array ();
var intvalue;
var lngproduct = 0;
var intcheckdigit;
var intstrlen = num.length;
var idNumber = num; Initialize if (Intstrlen!= && (Intstrlen!=)) {return false;}//check and set value for (i=0;i<in tstrlen;i++) {Vararray[i] = Idnumber.charat (i); if ((vararray[i) < ' 0 ' | | vararray[i] > ' 9 ') && (i!= 17)) {return false;}
else if (I <) {Vararray[i] = vararray[i] * factorarr[i];} if (Intstrlen = =) {//check date var Date8 = idnumber.substring (6,14); if (isDate8) = False) {return false;}/  /Calculate the sum of the products for (i=0;i<17;i++) {lngproduct = lngproduct + vararray[i];}//Calculate the Check
Digit Intcheckdigit = paritybit[lngproduct% 11]; Check last digit if (VararraY[17]!= intcheckdigit) {return false;}} else{//length is//check date var date6 = idnumber.substring (6,12); if (isDate6) = = False) {return false;} R
Eturn true; /** * To determine whether the "YYYYMM" type period * */function IsDate6 (sdate) {if (!/^[0-9]{6}$/.test)) {return false;} var year, Sdate,
Day
Year = sdate.substring (0, 4);
month = sdate.substring (4, 6); if (Year < 1700 | | |/year > 2500) return False if (Month < 1 | | month >) return false return True}/** * judgment is  "YYYYMMDD" type of period * */function IsDate8 (sdate) {if (!/^[0-9]{8}$/.test (sdate)) {return false;} var year, month, day;
= sdate.substring (0, 4);
month = sdate.substring (4, 6);
Day = sdate.substring (6, 8); var iamonthdays = [31,28,31,30,31,30,31,31,30,31,30,31] if (Year < 1700 | | | |, year > 2500) return False if ((4) = = 0 && (year% 100!= 0)) | | (Year% 400 = 0))
iamonthdays[1]=29; if (Month < 1 | | month >) return False if (Day < 1 | | day > IAMONTHDAYS[MONTH-1]) return False return True}//ID number Verification JQuery.validator.addMethod ("Idcardno", function (value, Element) {return this.optional (el Ement) | | 
Isidcardno (value);
"Please enter your ID number correctly"); Alphanumeric JQuery.validator.addMethod ("Alnum", function (value, Element) {return this.optional (element) | |/^[a-za-z0-9]+$
/.test (value);
"Only English letters and numbers" are included; ZIP Code verification JQuery.validator.addMethod ("ZipCode", function (value, Element) {var Tel =/^[0-9]{6}$/; return this.optional (E Lement) | |
(Tel.test (value));
"Please fill in the ZIP code correctly"); Chinese character JQuery.validator.addMethod ("Chcharacter", function (value, Element) {var Tel =/^[\u4e00-\u9fa5]+$/; return this.op tional (Element) | |
(Tel.test (value));
"Please input Chinese characters"); Character Minimum length verification (one Chinese character length is 2) jQuery.validator.addMethod ("Stringminlength", function (value, element, param) {var length =
Value.length; for (var i = 0; i < value.length i++) {if (Value.charcodeat (i) > 127) {length++.}} return This.optional (elemen T) | |
(length >= param);
}, $.validator.format ("length cannot be less than {0}!")); Character Maximum length validation (one in Chinese characters longDegree 2) JQuery.validator.addMethod ("Stringmaxlength", function (value, element, param) {var length = value.length; for (var i = 0; i < value.length; i++) {if (Value.charcodeat (i) > 127) {length++}} return This.optional (Element) | |
(length <= param);
}, $.validator.format ("length cannot be greater than {0}!")); Character Validation JQuery.validator.addMethod ("string", function (value, Element) {return this.optional (element) | |/^[\u0391-\
Uffe5\w]+$/.test (value);
}, "Do not allow special symbols!"); Mobile number verification JQuery.validator.addMethod ("mobile", function (value, Element) {var length = Value.length; return this.optional (Element) | | (length = &&/^ ((13[0-9]{1}) | (
15[0-9]{1})) +\d{8}) $/.test (value));
}, "mobile phone number format wrong!"); Phone number verification JQuery.validator.addMethod ("Phone", function (value, Element) {var Tel =/^ (\d{3,4}-?)?
\d{7,9}$/g; return this.optional (Element) | |
(Tel.test (value));
"The phone number format is wrong!"); ZIP Code verification JQuery.validator.addMethod ("ZipCode", function (value, Element) {var Tel =/^[0-9]{6}$/; return this.optional (E Lement) | | (Tel.test (value));
}, "Postal code format is wrong!"); 
JQuery.validator.addMethod ("Begin", function (value, element, param) {var begin = new RegExp ("^" + param) must be validated at the beginning of a specific string. return this.optional (Element) | |
(Begin.test (value));
}, $.validator.format ("must begin with {0}!")); Verify that two input values are not the same jQuery.validator.addMethod ("Notequalto", function (value, element, param) {return value!= $ (param). Val (
);
$.validator.format ("Two input cannot be the same!"); The validation value is not allowed to be equal to the specific value JQuery.validator.addMethod ("NotEqual", function (value, element, param) {return value!= param;}, $.valid
Ator.format ("Input value not allowed to {0}!")); The validation value must be greater than a specific value (not equal to) JQuery.validator.addMethod ("GT", function (value, element, param) {return value > param;}, $.valid
Ator.format ("Input value must be greater than {0}!"));
Verify that the number of decimal places cannot exceed two-bit jQuery.validator.addMethod ("decimal", function (value, Element) {var decimal =/^-?\d+ (\.\d{1,2})? $/; return this.optional (Element) | | (Decimal.test (value));

Jquery.validate usage

April 12, 2010, Monday 14:33

Name return type description

Validate (Options) return: Validator Verify the selected form

Valid () return: Boolean Check to see if validation passes

Rules () return: Options return the validation rules for elements

Rules (Add,rules) return: Options Add validation rules

Rules (Remove,rules)

Jquery.validate is a very good validation framework based on jquery, where we can quickly validate some of the common inputs and expand our own authentication methods, and also have great support for internationalization.

Jquery.validate Official website: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Use usage:

1, first download jquery.js and Jquery.validate.js and the introduction of JS file (Note: jquery must be introduced before jquery.validate.js, otherwise it will be an error)

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

2. Write the form code that needs to be validated and write the verification code (there are two ways to write the validation code, first use the common way)

var validator = $ ("Formid"). Validate ({//#formId为需要进行验证的表单ID
errorelement: "div",//use "div" tag to mark Error, default: "Label"
wrapper: "Li",//Use "Li" label and then put the top errorelement wrapped up
errorclass: "Validate-error",//Wrong hint CSS class name "error"
onsubmit:true,//whether the commit is authenticated, default: True
onfocusout:true,//whether to validate when the focus is obtained, by default: True
onkeyup:true,//whether to authenticate when tapping the keyboard, default: True
onclick:false,//whether to validate on mouse clicks (General validation Checkbox,radiobox)
focuscleanup:false,//Remove the error prompt when the element that fails validation obtains the focus
rules: {
loginName: {//required validation of the input box name
required:true//verification condition: Required
},
Loginpassword: {// The input box name required:true,//validation condition required to be validated:
required
minlength:5//verification Condition: Minimum length of 5
},
email: {//input box name to be validated
required:true,//Verification Condition: Required
email:true//Verification Condition: format is email
}
,
messages: {
loginName: {
Required: "User name is not allowed to be empty!" Verify failed Message
},
Loginpassword: {
required: "Password is not allowed to be empty!",
Minlength:jQuery.format ("password at least {0} characters!")
Email:
{
required: "Email is not allowed to be empty",
email: "Email address format Error!"
}
}

2, the use of meta-string authentication, that is, the validation content and write class (note that the meta string requires the introduction of jquery.metadata.js files)

<script type= "Text/javascript" src= "jquery.js" ></script> <script type= "Text/javascript" Jquery.metadata.js "></script> <script type=" Text/javascript "src=" Jquery.validate.js "></script" > <form id= "Validate" action= "Admin/transfer!save.action" method= "POST" > <input type= "text" class= " Required "name=" Entity.name "/> <input type=" text "class=" email "name=" entity.email "/> <input" type= "submit "class=" button "value="/> </form> <script type= "Text/javascript" > $ (document). Ready (function () {$ ( "#formId"). Validate ({//#formId为需要进行验证的表单ID meta: "Validate"//to validate (Validate content and write Class) by using meta string errorelement: "Div" ,//Use the "div" tag to mark errors, the default: "Label" wrapper: "Li",//Use the "LI" tag and then errorelement the top of the package Errorclass: "Validate-error",//Wrong hint CSS class name
"Error" onsubmit:true,//whether the commit is authenticated, default: True onfocusout:true,//whether to validate when the focus is obtained, default: True onkeyup:true,//whether to authenticate when tapping the keyboard, default: True onclick:false,//whether to verify on mouse clicks (General validation Checkbox,radiobox) focuscleanup:false,//when failedThe proof element gets the focus and removes the error prompt}); }) </script>

Note: In STRUTS2 applications you often use an input form that encounters a name= "Entity.name" (that is, when name contains commas or other special symbols), we can enclose the name in quotation marks (""), such as:

Rules: {
"entity.loginname": {//required validation of the input box name
required:true//verification condition: Required
}
},
messages: {
" Entity.loginname ': {
required: ' User name is not allowed to be empty! ' Validating messages that were not passed
}
}

You can give me email:happyczx@126.com welcome to discuss issues with Java technology

This part of the code from the Payj open source payment system, the Java Open Source project has a lot of excellent Struts2 spring hibernate jquery framework of the application of the source code, is worth a look. Recommend here first, hehe ...

Ps:jquery Validate Validation rules

(1) Required:true must be lost field
(2) Remote: "check.php" use Ajax method to invoke check.php validate input value
(3) Email:true must enter the correct format email
(4) Url:true must enter the URL in the correct format
(5) Date:true must enter a date in the correct format
(6) Dateiso:true must enter the correct format of the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, do not verify the validity
(7) Number:true must enter a valid number (negative, decimal)
(8) Digits:true must enter an integer
(9) CreditCard: Must enter the legal credit card number
(a) Equalto: "#field" input value must be the same as #field
(one) Accept: Enter a string with a valid suffix name (the suffix of the uploaded file)
(Maxlength:5) A string with a maximum of 5 input length (Chinese characters are counted as one character)
(Minlength:10) A string with a minimum input length of 10 (Chinese characters are counted as one character)
(rangelength:[5,10] Enter a string that must be between 5 and 10) (Chinese characters are counted as one character)
() range:[5,10] The input value must be between 5 and 10
() Max:5 input value cannot be greater than 5
(min:10) input value cannot be less than 10

Jquery Validate Submit Submission

Submithandler: A function that is run after validation, in which the form submits a function, or the form is not submitted
$ (". Selector"). Validate ({submithandler:function (form) {$ (form). Ajaxsubmit ();//Functions with jquery form})

Jquery Validate Error Tip dom

. Errorplacement:callback Default: Put the error message behind the validated element
Indicates where the error was placed, by default: Error.appendto (Element.parent ()), where the error message is placed behind the validated element

Errorplacement:function (Error, Element) {
error.appendto (element.parent ());
}

To set the style of the error hint, you can increase the icon display, like:

Input.error {border:1px solid red;}
Label.error {
Background:url ("./demo/images/unchecked.gif") no-repeat 0px 0px;
padding-left:16px;
padding-bottom:2px;
Font-weight:bold;
Color: #EA5200;
}

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.