Jquery.validate Custom Authentication Method Addmethod

Source: Internet
Author: User
Tags commit wrapper
$ (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<intstrlen;i++) {Vararray[i] = Idnumber.charat (i);
         if ((Vararray[i] < ' 0 ' | | | vararray[i] > ' 9 ') && (i!=)) {return false;
         else if (I <) {Vararray[i] = vararray[i] * Factorarr[i];
         } if (Intstrlen = =//check date var Date8 = idnumber.substring (6,14);
         if (IsDate8 (date8) = = 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 (date6) = = False) {return false;
 } return true;
   /** * To determine whether the "YYYYMM" type period * */function IsDate6 (sdate) {if (!/^[0-9]{6}$/.test)) {return false;
   Var year, month, 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}/**
   * To determine whether the "YYYYMMDD" type of period * */function IsDate8 (sdate) {if (!/^[0-9]{8}$/.test (sdate)) {return false; Var year, MonTh, day;
   Year = 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 ((yea R% 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 Retu RN true}//ID number Verification JQuery.validator.addMethod ("Idcardno", function (value, Element) {return this.optional (elemen T) | |   
 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 (Element) | |
 (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.optional (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}!")); Maximum character length verification (a Chinese character length of 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 (elemen T) | |
(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

}, $.validator.format ("input value is 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)                           Back: Validator Verify that the selected form valid () is returned: Boolean checks to see if validation passes the rules () Back: Options returns the validation rules for the element rule (add,rules) return: Options Increase validation rule rules (Remove,rules) jquery

Validate is a very good validation framework based on jquery that allows us to quickly validate some of the common inputs and expand our own authentication methods, and it also has great support for internationalization. Jquery.validate Official Website: http://bassistance.de/jquery-plugins/jquery-plugin-validation/usage: 1, First download jquery.js and jquery.validate.js and introduce JS file (Note: jquery must be introduced before jquery.validate.js, or it will complain) &Lt;script type= "Text/javascript" src= "jquery.js" ></script> <script type= "Text/javascript" src= "JQUERY.V" Alidate.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 using the normal way) var validator = $ (" Formid "). Validate ({//#
   Formid to verify the form ID errorelement: "div",//Use the "div" tag to mark the error, default: "Label" wrapper: "Li",//Use the "Li" label and then wrap up the errorelement above Errorclass: "Validate-error",//Error prompted CSS class name "error" onsubmit:true,//whether the commit is validated, default: True onfocusout:true,//whether to validate when the focus is obtained, default : True onkeyup:true,//whether to authenticate when tapping the keyboard by default: True onclick:false,//whether to verify on mouse clicks (General validation Checkbox,radiobox) focuscleanup:false,/ /When the element that fails validation obtains the focus, and removes the error hint rules: {loginName: {//The input box name to be validated require d:true//verification Condition: required}, Loginpassword: {//input box name to be validated req uired:true,//Verification Conditions: required minlength:5//Verification conditions: Minimum length of 5}, email
       : {///required to validate the input box name                 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 enter at least {0} characters!") 
                    Email: {Required: "Email is not allowed to be empty", email: "Email address format is wrong!" } 2, using Meta string authentication, that is, validating content and writing class (note that meta string requires the introduction of jquery.metadata.js files) & Lt;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"/> & Lt;input type= "Submit" class= "button" value= "Submit"/> </form> <script type= "Text/javascript" > $ (document) . Ready (Function () {$ ("#formId"). Validate ({//#formId为需要进行验证的表单ID meta: "Validate"/) validate using meta string (Verify content and write class Errorelement: "div",//Use the "div" tag to mark the error, the default: "Label" wrapper: "Li",//Use the "LI" tag and then the top of the errorelement wrapped up Errorclass: "Val  Idate-error ",//Error prompted CSS class name" error "onsubmit:true,//whether the commit is validated, 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 validate on mouse clicks (General validation Checkbox,radiobox) focuscleanup:false,//when elements that have not been validated receive the focus
and remove 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 Not allowed to be empty! " Verify failed messages} can I have email:happyczx@126.com welcome to discuss problems with Java technology The above part of the code comes from Payj Open source payment system, this JAV A open source project has a lot of excellent Struts2 spring hibernate jquery and other framework of the application of the source code, is worth a look.

Recommend here first, hehe .... Attachment: Built-in authentication method: Required () return: Boolean Required validation element required (dependency-expression) returns: A Boolean required element relies on the result of an expression required ( Dependency-callback) Returns: The Boolean required element relies on the result remote (URL) Return of the callback function: Boolean request remote checksum. A URL is usually a remote calling method MinLength (length) return: Boolean Set minimum length maxlength (Long) return: Boolean set maximum length Rangelength (range) return: Boolean Set a length range [Min,max] min (value) return: Boolean set Max Max (value) return: Boolean set minimum email () return: Boolean verify e-mail format range (range) return: Boo Lean set Value range URL () return: Boolean Validate URL format date () return: Boolean validation date format (similar to 30/30/2008 format, no validation date accuracy only validate format) Dateiso () return: Boolean Validating the ISO type date format Datede () returns: boolean-authenticated date format (29.04.1994 or 1.1.2006) number () returns: Boolean validates decimal digits (including decimal) digits () returns: Boolean Validation Integer CREDITCARD () return: Boolean Authentication credit card number accept (extension) returns: Boolean verifies the same suffix name string Equalto (Other) returns: Boolean verifies that the contents of two input boxes are the same phoneus () returns: Boolean Verify American phone number validate () Optional: Debug: Debug mode (Form not submitted): $ (". Selector"). Validate ({debug:true}) set Debug to default: $.validato R.setdefaults ({debug:true}) Submithandler: A function that is run after validation is added with the form's submitted function, otherwise the form will not commit $ (". Selector"). Validate ({Submithandle
   R:function (Form) {$ (form). Ajaxsubmit (); }) Ignore: Does not validate for certain elements $ ("#myform"). Validate ({ignore: ". Ignore"}) Rules: Custom rules, Key:value form, key is the element to be validated, value can be a string or
   Like $ (". Selector"). Validate ({rules:{name: "Required", email:{required:true, email:true} }) messages: Custom hint information key:value the form key is the element to validate, the value is a string or function $ (". Selector"). Validate ({rules:{name: "Required", E mail:{required:true, Email:true}}, messages:{name: "Name cannot be empty", email:{Requir Ed: "E-mail can not be empty", email: "E-mail address is not correct"}}) groups: Validation of a set of elements, with a false hint, with error placement control the error letterWhere to put $ ("#myform"). Validate ({groups:{username: "FName lname"}, Errorplacement:function (error,element) {if (ele Ment.attr ("name") = = "FName" | |
     Element.attr ("name") = = "LName") error.insertafter ("#lastname");
   else Error.insertafter (element); }, Debug:true}) Onubmit Boolean default: True to validate $ (". Selector") at commit time. Validate ({onsubmit:false}) onfocusout Boolean default: t Rue whether the $ (". Selector") is validated when the focus is obtained. Validate ({onfocusout:false}) onkeyup Boolean default: True to verify $ (". Selector") when tapping the keyboard. Validate ({onkeyup:false}) onclick Boolean default: True to verify when mouse clicks (General validation Checkbox,radiobox) $ (". Selector"). Validate ({onclick:fals e}) Focusinvalid Boolean default: True when a form is submitted, a form that is not validated (the first or the failed form that has the focus before it is submitted) receives the focus $ (". Selector"). Validate ({focusinvalid: False}) Focuscleanup Boolean default: False when the element that has not been validated obtains the focus and removes the error prompt (avoid and focusinvalid.) $ (". Selector"). Validate ({FOCUSCL Eanup:true}) Errorclass String default: "Error" specifies the CSS class name for the error hint, you can customize the style of the error hint $ (". Selector"). Validate ({errorclass: "Invalid"}Errorelement string defaults to: "Label" uses what label to mark the error $ (". Selector"). Validate errorelement: "Em"}) wrapper String uses what label to put the top Erro Relement wrapped up $ (". Selector"). Validate ({wrapper: "Li"}) Errorlabelcontainer selector put the error message uniformly in a container $ ("#myform").

Validate ({errorlabelcontainer: "#messageBox", wrapper: "Li", submithandler:function () {alert ("submitted!")}) ShowErrors: With a function, you can display the total number of failed validation elements $ (". Selector"). Validate ({showerrors:function (errormap,errorlist) {$ ("#su
        Mmary "). HTML (" Your form contains "+ this.numberofinvalids () +" Errors,see details below. ");
   This.defaultshowerrors (); }) Errorplacement: With a function, you can customize where the error is put $ ("#myform"). Validate ({rrorplacement:function (error,element) {error.appendto
   (Element.parent ("TD"). Next ("TD");
        }, Debug:true}) Success: The element to be validated is validated by the action, if followed by a string, as a CSS class, can also be followed by a function $ ("#myform"). Validate ({success: "valid",
Submithandler:function () {alert ("submitted!")}}) Highlight: Can give the element that fails to validate to add effect, flicker waits for Addmethod (Name,methoD,message Method: Parameter name is the name of the added method is a function that receives three arguments (Value,element,param) value is the value of the element, the element is itself param is a parameter, We can use Addmethod to add validation methods other than built-in Validation methods such as having a field that only loses one letter, the range is a-f, as follows: $.validator.addmethod ("AF",
   function (Value,element,params) {if (value.length>1) {return false;
   } if (Value>=params[0] && value<=params[1]) {return true;
   }else{return false;
}, "must be a letter, and a-f"); When used, such as the id= "username" of a form field, the first argument in the rules that writes username:{af:["A", "F"} Addmethod is the name of the added authentication method, which is the third parameter of the AF addmethod. is a custom error prompt, and here's the hint: "must be a letter, and A-f" the second parameter of the Addmethod, which is a function, is more important and determines the way in which this validation method is written if there is only one argument, write directly, if AF: "A", then A is the only parameter,

If multiple parameters, used in [], separated by commas}, $.validator.format ("Number of decimal places can not exceed two digits!")); });

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.