jquery Verification Plugin

Source: Internet
Author: User
Tags add date format commit empty key range valid

Learning points:
1. Use the Validate.js plugin
2. Default validation rules
3.validate () Methods and options
4.validate.js Other Features


Verification Plug-in (Validate.js) is a plug-in that verifies the legality of regular form data. Use it, greatly liberated in the form of the complex verification process, and the error hint to improve the display also increased the user experience.



A Using the Validate.js Plug-in
Website Download: http://bassistance.de/jquery-plugins/ The most important file for Jquery-plugin-validation is validate.js, and there are two optional secondary files: Additional-methods.js (Control class method) and Message_ Zh.js (prompt Chinese) file (actual use, please use min compressed version).

First step: Introduce Validate.js

Step two: Execute in JS file
$ (' #reg '). Validate ();

Two Default validation rules
The default validation rules for Validate.js are written in two forms: 1. Control property mode; 2.JS key-value-to-pass method.

Verify "required and no less than two bits" using a control method



Note: The default rule is to set the Boolean value, write directly to the class can be implemented. If it is a number or array range, you can use the attribute = value directly. And for the wrong hint, you can introduce Chinese documents, or directly replace it.
Use the JS object key to set the argument

$ (' #reg '). Validate ({rules
: {
User: {/////* Only one rule,
required:true, Direct user: ' Required ',
minlength:2,
},
},
messages: {
User: {
  
    required: ' account must not be empty! ',
minlength: ' Account number must not be less than 2 digits! ',
},
}
});
  

Note: The first form cannot set the specified error message. We recommend using the second form, and the second form also avoids HTML contamination.


All Rules Demo

$ (' #reg '). Validate ({      rules: {        Email: {& nbsp;           Email:true,         },         URL: {             url:true,        },          Date: {            date:true,         },         Dateios: {             dateios:true,        },          Number: {            number : True,        }       &Nbsp;  digits: {            digits:true,   & nbsp;    },         CreditCard: {             creditcard:true,        },          min: {            min : 5,        },         range: {  &
nbsp;         range: [5],        },         rangelength: {            Rangelength: [5,10],        },          Notpass: {            Equalto: ' #pass ',//here to is uppercase T        }    }

Three. The methods and options for validate ()
In addition to the default validation rules, Validate.js provides a number of other properties and methods for developers to use. For example, debug properties, the error hint location a series of more useful options.
//jquery.format formatting Error tips

$ (' #reg '). Validate ({
rules: {
User: {
required:true,
minlength:5            ,
rangelength: [5,10]
},
},
messages: {
User: {
Required: ' Account must not be empty! ',
Minlength:jQuery.format (' account number must not be less than {0} bit! '),
Rangelength:jQuery.format (' account number is limited to {0}-{1} bit! '),
},
},
});

Open Debug mode Prohibit commit
$ (' #reg '). Validate ({
Debug:true,
});


Set debug mode to default, you can prevent multiple forms from submitting
$.validator.setdefaults ({
Debug:true,//Still normal to verify, but not submitted to the specified page for easy debugging
});


Use other methods instead of default submission
Submithandler:function (form) {
Can perform Ajax commits without debug:true blocking the commit
},


Ignore a field validation
Ignore: ' #pass ',


Group Error Tip
Groups: {
Myerror: ' User pass ',
},


Show group Error Tips
Focusinvalid:false,
Errorplacement:function (Error, Element) {
$.each (Error, function (index, value) {
$ ('. Myerror '). HTML ($ ('. Myerror '). HTML () + $ (value). HTML ());
})
},


Group error hint, separate
Groups: {
Error_user: ' User ',
Error_pass: ' Pass '
},


Specify the location of the group error (Recommended!!) )

1 errorplacement:function (Error, Element) {
2 Error.appendto ('. Myerror ');
3},




Set the class name of the error hint

Errorclass: ' Error_list ',


Set the label for the error tip
Errorelement: ' P ',

PS: The default class name is "error" and the default error hint label is.


Unified Parcel Error Tip

(First of all, the error message tag outside a layer of Li, and then the HTML file in advance set the error message display element class is error OL, the two lines of code will be the error message form a list style)
Errorlabelcontainer: ' Ol.error ',
Wrapper: ' Li ',


Set class to load after success
Success: ' Success ',

PS: After the validation is successful, you will add a sucess class name to the label label and then the CSS style that is successful based on this setting. In addition, note: After the success of the corresponding input elements of the class value will have an error into valid, this can also be based on the class value of the CSS style, like the success of the prompts displayed in the input, rather than using success display in the input outside.




Load class with method and add text
Success:function (label) {
Label.addclass (' success '). Text (' OK ');
},


Highlight elements with errors, color-changing
Highlight:function (element, Errorclass) {
$ (Element). fadeout (function () {
$ (Element). FadeIn ()
})
},

Highlight elements with errors, color-changing
highlight:function (element, Errorclass) {
$ (element). css (' border ', ' 1px solid red ');
} ,

//successful element removal error highlighting
unhighlight:function (element, Errorclass) {
$ (element). css (' border ', ' 1px solid #ccc ');
},

Get information when form is submitted
Invalidhandler:function (event, Validator) {
var errors = Validator.numberofinvalids ();
if (errors) {
$ ('. Myerror '). HTML (' You have ' + errors + ' form elements to fill out illegally!) ');
}
},

Get the error prompt handle without submitting the value in time
showerrors:function (Errormap, errorlist) {
var errors = This.numberofinvalids ();
if (errors) {
$ ('. Myerror '). HTML (' You have the ' + errors + ' form elements to fill out illegally!    ');
} else {
$ ('. Myerror '). Hide ();
}
this.defaultshowerrors (); Execute default Error
},


//Get error prompt handle, errorlist
showerrors:function (Errormap, errorlist) {
alert (errorlist[0   ].message);   Get error message
alert (errorlist[0].element); Table cell element for the current error.

Four Validate.js Other Features
With Remote:url, you can perform AJAX validation on the form, and the default is to commit the currently validated value to the remote address. If you need to submit additional values, you can use the data option.
Using AJAX validation

Rules: {
User: {
required:true,
minlength:2,
remote: ' user.php ',
},
},

user.php Content

if ($_get[' user '] = = ' Alex ') {
echo ' false ';
} else {
Echo ' true ';
}
?>

Note: Remote addresses can only output ' true ' or ' false ' and cannot output other values.
Pass multiple values to the remote side at the same time

Pass: {
required:true,
minlength:6,
remote: {
URL: ' user.php ',
type : ' POST ',
dataType: ' JSON ',
data: {
user:function () {
re            Turn $ (' #user '). Val ();
},
},
},
},

user.php Content

      if ($_post[' user ')!= ' Alex ' $_post[' pass ']!= ' 123456 ') {
   &N bsp;    echo ' false ';
   } else {
        echo ' true ';
   }
?

The

Validate.js provides default values for event firings, most of which are not changed.
//Cancel commit verification
Onsubmit:false,//default is True
Note: setting to False results in direct legacy commits, does not implement validation, and is typically used for Keyup/click/blur validation submissions.

 

//Setting mouse left does not trigger validation
Onfocusout:false,//default to True


//setting keyboard press trigger does not triggering validation
Onkeyup:fal SE,//default to True

Note: When set, the browser that is tested is not triggered either false or true.


//settings Click CheckBox and Radio Click Do not trigger validation
Onclick:false,//default to True


//Set error prompt, unable to get focus
FOCUSINV The single element sets the title value, and messages is the default, the error message of the title value is read, and we can set the ignoretitle:true to True to mask this feature.

Ignoretitle:true,//default to False


//Determine whether the elements validated by the form are all valid
Alert ($ (' #reg '). valid ());//All valid return True
The

Validate.js provides the rules method for validating each form element individually, providing not only add addition validation, but also the ability to remove validation.


//Add one form validation to user

$ (' #user '). Rules (' Add ', {
required:true,
minlength:2,
messages: {
required: ' Account no Have to be empty! ',
Minlength:jQuery.format (' account number must not be less than {0} bit! '),
}
});

Delete all validation rules for user
$ (' #user '). Rules (' Remove ');


Delete specified validation rule for user
$ (' #user '). Rules (' Remove ', ' minlength min Max ');

To add a custom validation
$.validator.addmethod (' Code ', function (value, Element) {
var tel =/^[0-9]{6}$/;
return this.optional (Element) (Tel.test (value));
}, ' Please fill in your zip code correctly ';

Invoke Custom Validation
Rules: {
Code: {
Required:true,
Code:true,
}
}


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.