jquery Authentication Plugin

Source: Internet
Author: User

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

Validation plug-in (validate.js) is a plug-in that validates the legitimacy of regular form data. Using it, the complex verification process on the form is greatly liberated, and the improvement of the error display also increases the user experience.

A Using the Validate.js plugin
Official website Download: http://bassistance.de/jquery-plugins/ Jquery-plugin-validation most important file is validate.js, and there are two optional auxiliary files: Additional-methods.js (Control class mode) and Message_ Zh.js (hint Chinese) file (in practice, use min compressed version).

First step: Introduce Validate.js
<script type= "Text/javascript" src= "Js/jquery.validate.js" ></script>
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 pair-transfer method.

Verify that "required and not less than two bits" is validated using the control method

<input type= "text" class= "required" minlength= "2" name= "user" id= "user"/>

Note: The default rule is set to the Boolean value, directly written into the class can be implemented. If it is a number or array interval, you can use the property = value directly. For the error prompt, can be introduced in Chinese files, or directly replaced.
Use the JS object key value to set the method of parameter transfer

$('#reg'). Validate ({rules: {User: {//There is only one rule.Required:true,//Direct User: ' Required ',MinLength:2, },}, messages: {User: {required:'the account number must not be empty! ', minlength:'account number must not be less than 2 bit! ',        },    }});

Note: The specified error message cannot be set because of the first form. We recommend using the second form, the second form also avoids the HTML pollution.

All Rules Demo

$('#reg'). Validate ({rules: {email: {Email :true,}, url: {URL:true,}, Date: {date:true,}, Dateios: {dateios:true,}, Number: {number:true,} digits: {digits:true,}, CreditCard: {creditcard:true,}, min: {min:5,}, Range: {range: [5,Ten],}, Rangelength: {rangelength: [5,Ten],}, Notpass: {equalto:'#pass',//here to is the uppercase T        }    },})

Three 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, error location, a series of more useful options.
Jquery.format Formatting Error hints

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

Enable debug mode prohibit commit
$ (' #reg '). Validate ({
Debug:true,
});


Set debug mode to default, you can prohibit multiple form submissions
$.validator.setdefaults ({
Debug:true,//can still be verified normally, but is not submitted to the specified page for ease of debugging
});


Use other methods instead of default submissions
Submithandler:function (form) {
You can perform AJAX submissions without debug:true blocking the commit
},


Ignore a field validation
Ignore: ' #pass ',


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


Display the group's error message
Focusinvalid:false,
Errorplacement:function (Error, Element) {
$.each (Error, function (index, value) {
$ ('. Myerror '). HTML ($ ('. Myerror '). HTML () + $ (value). HTML ());
})
},


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


Specify the location of the group's errors (recommended!!) )

errorplacement:function (Error, Element) {error.appendto ('. Myerror');}, 

Set the class name for the error prompt

Errorclass: ' Error_list ',


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

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


Unified Package Error Tips

(The error message label is wrapped outside the first layer of Li, and then the HTML file in advance to set the error message display element class is the error of OL, these two lines of error messages form a list style)
Errorlabelcontainer: ' Ol.error ',
Wrapper: ' Li ',


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

PS: After validation succeeds, a sucess class name is added to the label label, and then the CSS style can be successfully followed by this setting. Also note: After success, the corresponding input element of the class value will be changed to valid, so you can also set the CSS style according to the class value, the sample after the successful prompt display in input, instead of using success display outside of input.


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


//Highlight the element with error, 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 moved out error highlight unhighlight:function (element, Errorclass) {$ (Element). CSS ( /c12>'border'1px solid #ccc');},

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

//get error prompt handle without committing to get value in timeshowerrors:function (Errormap, errorlist) {varErrors = This. Numberofinvalids (); if(Errors) {$ ('. Myerror'). HTML ('you have'+ Errors +'a FORM element is illegal to fill! '); } Else {        $('. Myerror'). Hide (); }     This. Defaultshowerrors ();//Execute default error},//get the error prompt handle, errorlistshowerrors:function (Errormap, errorlist) {alert (errorlist[0].message);//get the error messageAlert (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 by submitting the currently validated value to the remote address by default. If you need to commit additional values, you can use the data option.
Using AJAX authentication

rules: {    User: {        true,        2,        'user.php  ',    },},

user.php Content

<? PHP     if ($_get['user'Alex')        {'  False';     Else {        'true';    }? >

Note: The remote address 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 () {return$('#user'). Val (); },        },    },},

user.php Content

<?PHPif($_post['User'] !='Alex'|| $_post['Pass'] !='123456') {echo'false'; } Else{echo'true'; }?>

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

Setting the mouse away does not trigger validation
Onfocusout:false,//default is True


Set keyboard press to bounce does not trigger validation
Onkeyup:false,//default is True

Note: As soon as it is set, the browser in the test is not triggered either by false or true.


Set Click CheckBox and Radio Click Do not trigger validation
Onclick:false,//default is True


Unable to get focus after setting error prompt
Focusinvalid:false,//default is True


When prompted for errors, hide the error prompt, cannot be used with focusinvalid, conflict
Focuscleanup:true,//default = False
If the form element is set to the title value, and messages is the default, the error message of the title value is read, and we can block this function by Ignoretitle:true, set to True.

Ignoretitle:true,//default = False


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


Validate.js provides a rules method that can independently validate each form element, providing add validation and remove validation.


Add a form validation to user

$ ('#user'). Rules ('add', {    true,     2 ,    messages: {        ' account must not be empty!  ',        minlength:jQuery.format (' account must not be less than {0} bit!  '),    }});

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


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

//Add custom Validation$.validator.addmethod ('Code', function (value, Element) {varTel =/^[0-9]{6}$/; return  This. Optional (Element) | |(Tel.test (value)); }, 'please fill in your zip code correctly');//Invoking custom Validationrules: {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.