问题
I have a quiz, and i need to add some validation to a confirm email address field, basically it just has to match the email address given in the above field. I am using the following javascript, can i add something in here which will make sure the emails match?
if ($('#mtQuiz').length > 0) {
$('#myQuiz').validate({
errorElement: "em",
errorContainer: $("#warning"),
rules: {
'entry[first_name]': 'required',
'entry[last_name]': 'required',
'entry[email]': {
required: true,
email: true
},
'entry[confirm_email]': {
required: true,
email: true
}
},
messages: {
'entry[first_name]': 'Please enter first name',
'entry[last_name]': 'Please enter last name',
'entry[email]': {
required: ' Please enter a valid email address',
minlength: 'Not a valid email address'
},
'entry[confirm_email]': {
required: ' Please make sure email matches above',
minlength: 'Does not match above email address'
}
}
});
}
回答1:
if ($('#mtQuiz').length > 0) { // <- unnecessary and superfluous
$('#myQuiz').validate({
// options, etc.
});
}
You're using jQuery so you don't need to check for the existence of #myQuiz with if ($('#mtQuiz').length > 0). If the #myQuiz element doesn't exist, jQuery will simply ignore it without any errors.
This is all you need to do...
$('#myQuiz').validate({ // initialize the plugin
// options, etc.
});
To match the value of another field, simply use the equalTo rule. While using the equalTo rule, there is no need to duplicate any of the other rules since equalTo will always force the value to match the primary field's value which already followed its rules.
$('#myQuiz').validate({
// options, etc.,
rules: {
'entry[first_name]': 'required',
'entry[last_name]': 'required',
'entry[email]': {
required: true,
email: true
},
'entry[confirm_email]': {
//required: true, // <- redundant, not needed with 'equalTo'
//email: true // <- redundant, not needed with 'equalTo'
equalTo: '[name="entry[email]"]' // <- any valid jQuery selector
}
},
// other options, etc.
});
DEMO: http://jsfiddle.net/JCY2E/
回答2:
Have a look to equalTo method.
$('#myQuiz').validate({
...
rules: {
...
'entry[confirm_email]': {
equalTo: "entry[email]"
}
}
});
来源:https://stackoverflow.com/questions/22746091/jquery-validate-confirm-email-form-validation