How to validate a email address field with three rules with three customized messag开发者_运维技巧es in the div container. ie.
rules: {
email: {
validationRule: true,
email: true,
remote: '/ajax/emailDuplicationCheck.php'
}
}
if first one false message should be "validation rule failed"
if second one false(fail) "enter email address"
if third(remote) failed. message should be "Account already exist in database".
I can added one message for all rules but i want to customize the message with respect to the rules.
Try this:
$("#myForm").validate({ // Replace #myForm with the ID of your form
rules: {
email: {
required: true,
email: true,
remote: {
url: "/ajax/emailDuplicationCheck.php",
type: "post",
data: { email: function() {
return $("#email").val(); // Add #email ID to your email field
}
}
}
},
messages: {
email: {
required: 'Email address is required',
email: 'Please enter a valid email address',
remote: 'This email address has already been used'
}
},
errorPlacement: function(error) {
$("#response").html(error);
}
});
Hope this helps !
You can use custom validation rules along with your own custom messages for each rule.
For simplicity, here's an example of how to validate a 'username' input with three custom methods for validation (each with its' own error message):
// Add three custom methods first:
$.validator.addMethod("nameCustom", function(value, element) {
return this.optional(element) || /^[a-zA-Z ]+/.test(value);
}, 'Please use english letters only.');
$.validator.addMethod("noSpaceStart", function(value, element) {
return value.indexOf(" ") != 0;
}, "Name cannot start with a space");
$.validator.addMethod("noSpaceEnd", function(value, element) {
return value.lastIndexOf(" ") != value.length - 1;
}, "Name cannot end with a space");
$('#form_to_validate').validate({
rules: {
username: {
// Add the custom validation methods to the username input
noSpaceStart: true,
noSpaceEnd: true,
nameCustom: true,
// required and maxlength are built-in methods in the plugin and are ready to be used
required: true,
maxlength: 50
}
}
});
精彩评论