Custom Validation For Jquery Validate (two Method In One)
I would like to know, how can I call another custom validation method of jquery validate in my method to validate some data. For sample, I have a field called 'Document ID' that ca
Solution 1:
What about this?
jQuery.validator.addMethod("documentoId", function(value, element) {
if (value.length <= 11) {
jQuery.validator.methods.cpf.call(this, value, element);
}
elseif (value.length <= 14) {
jQuery.validator.methods.cnpj.call(this, value, element);
}
}, 'Documento inválido');
Full example changing the error message
jQuery.validator.addMethod("documento", function(value, element) {
// remove pontuações
value = value.replace('.','');
value = value.replace('.','');
value = value.replace('-','');
value = value.replace('/','');
if (value.length <= 11) {
if(jQuery.validator.methods.cpf.call(this, value, element)){
returntrue;
} else {
this.settings.messages.documento.documento = "Informe um CPF válido.";
}
}
elseif (value.length <= 14) {
if(jQuery.validator.methods.cnpj.call(this, value, element)){
returntrue;
} else {
this.settings.messages.documento.documento = "Informe um CNPJ válido.";
}
}
returnfalse;
}, "Informe um documento válido.");
Solution 2:
jQuery.validator.addMethod("cnpj", function(value, element) {
returnthis.optional(element) || /^[0-9]{2}.[0-9]{3}.[0-9]{3}?\/[0-9]{4}-[0-9]{2}$/.test(value);
}, "Formato: 00.000.000/0000-00");
Solution 3:
how about creating those function outside of the scope of the validation definition (i.e not using anonymous functions)?
functioncpfValide(value,element) {
//something
}
functioncnpjValide(value,element){
//something
}
jQuery.validator.addMethod("cpf", cpfValide, "CPF inválido!");
jQuery.validator.addMethod("documentoId", function(value, element) {
returncpfValidate(value,element) || cnpjValidate(value,element);
//..
}
Post a Comment for "Custom Validation For Jquery Validate (two Method In One)"