I want to customize the validations of my form using the addMethod function with the jQuery validator, but when I tried to add more than one method the validator seems to look only at the first one.
Here is the code:
jQuery.validator.addMethod("name", function(value, element) {
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{2,30}$/.test(value);
}, "please enter a valid name");
jQuery.validator.addMethod("surname", function(value, element) {
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}\-?[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}$/.test(value);
}, "please enter a valid surname");
$("#contactform").validate({
rules: {
firstname:{
required: true,
name: true,
minlength: 2,
maxlength: 30
},
lastname:{
required: true,
surname: true,
minlength: 2,
maxlength: 30
}
}
});
The issue is that on the last name I want to be able to add an '-' in case of a combined surname, I tried the regEx and it works exactly as I want to, but even if I call the method 'surname' in the rules of the field, it seems to elaborate the method 'name' anyway!
Thanks in advance for your help, I really don't understand what I'm missing here..
The issue is with your method name. The prop name
inside rules is already a predefined rule inside $.validator
like minLength
. If you change name
to anything but that it will work.
JS
$(document).ready(function(){
$.validator.addMethod("named", function(value, element){
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{2,30}$/.test(value);
}, "Please enter a valid name.");
$.validator.addMethod("surname", function(value, element){
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}\-?[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}$/.test(value);
}, "Please enter a valid surname.");
$("#contactform").validate({
rules: {
firstname: {
required: true,
named: true,
minlength: 2,
maxlength: 30
},
lastname:{
required: true,
surname: true,
minlength: 2,
maxlength: 30
}
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.