This article introduces the use of jquery. validate1.9.0 front-end verification. For more information, see
I. Use the jquery. form plug-in to submit a form using the jquery. validate plug-in
Symptom: When a form is submitted, the form is submitted as usual even if the front-end fails to pass the verification.
Solution:
The Code is as follows:
$ ('# MyForm'). submit (function (){
If (! $ (This). valid () return false; // Add this sentence OK
('.Error'{.html ('');
$ ("# Go"). prop ("disabled", true );
$ (This). ajaxSubmit ({
Type: "POST ",
// BeforeSubmit: showRequest,
DataType: 'json ',
Success: showResponse
});
Return false;
});
Instructions:
Custom submission method (ajax submission)
If ajax is used for submission, use the following two methods in combination with the verification framework:
1) Configure ajax submission using the submitHandler attribute. submithandler: When all the forms are verified, the configuration code will be called back. In this case, ajax is called for submission after the verification is passed.
2) use the valid method to listen to the form submit event and submit it again when $ ('# form'). valid () returns true.
You can use ajax to submit a form by listening to the form submit event. The complete sample code is as follows:
The Code is as follows:
$ (Document). ready (function (){
$ ('# MyForm'). submit (function (){
If (! $ (This). valid () return false;
('.Error'{.html ('');
$ ("# Go"). prop ("disabled", true );
$ (This). ajaxSubmit ({
Type: "POST ",
// BeforeSubmit: showRequest,
DataType: 'json ',
Success: showResponse
});
Return false;
});
Var validator = $ ("# myForm"). validate ({
Rules :{
Username: "required ",
Email :{
Required: true,
Email: true
}
},
Messages :{
Username: "enter your name ",
Email :{
Required: "Enter the Email address ",
Email: "enter the correct email address"
}
}
});
});
Function showResponse (jsonData, statusText)
{
If (statusText = 'success ')
{
$ ("# Go"). prop ("disabled", false );
If (jsonData. status = 1)
{
$ ("# Return" response .html (jsonData. message );
}
Else
{
$. Each (jsonData. errors, function (k, v ){
// $ ('# Output'). find ('ul'). append ('
'+ V +'');
$ ('. E _' + k).html (v );
});
}
}
}
Ii. Methods for controlling the location of error messages
Symptom 1:
I added a new verification code to the Registry ticket. When the verification result is incorrect, the error message goes to the front of the verification code. As shown in:
Purpose: To keep the error message behind the verification code
Symptom 2:
In red, I want to move to the end of (* required.
The above two phenomena can be used to control the location of error messages through the method 'errorplacement 'provided by jquery. validate, which is also convenient to use:
The Code is as follows:
ErrorPlacement: function (error, element)
{
Error. appendTo (element. parent ());
}