问题描述
我想知道,如何在我的方法中调用jquery validate的另一个自定义验证方法来验证某些数据.例如,我有一个名为文档ID"的字段,可以接受CPF或CNPJ(均为巴西文档),并且需要使用jquery validate对其进行验证.我正在做这样的事情:
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 can accept CPF or CNPJ (both are brazilians documents), and I need to validate it with jquery validate. I'm doing something like this:
jQuery.validator.addMethod("cpf", function(value, element) {
// my validation for CPF Documents
}, "CPF inválido!");
jQuery.validator.addMethod("cnpj", function(value, element) {
// my validation for CNPJ Documents
}, "CNPJ inválido!");
当我对每种类型都有一个字段但都只有一个字段时,两种方法都可以正常工作,我必须在文本字段上发现我的用户类型并进行验证,就像这样:
Both works fine when I have one field for each type but I have only one and I have to discovery what my user type on textfield and validate it, somethind like this:
jQuery.validator.addMethod("documentoId", function(value, element) {
if (value.lenght <= 11) {
// validation for CPF and change the message
}
else if (value.lenght <= 14) {
// validation for CNPJ and change the message
}
}, 'Documento inválido');
但是我不知道如何在另一个函数(documentId)中调用这些自定义函数(cpf和cnpj).
but I don't know how to call these custom functions (cpf and cnpj) inside my another function (documentId).
我该怎么办?以及如何更改自定义验证中的消息?
How can I do it? and how can I change the message inside my custom validation ?
谢谢!干杯!
如果您要查看的话,我已经在jsbin中发布了我的代码: http://jsbin.com /ijetex/5/edit
I've posted my code in jsbin, if you want to look: http://jsbin.com/ijetex/5/edit
推荐答案
这怎么办?
jQuery.validator.addMethod("documentoId", function(value, element) {
if (value.length <= 11) {
jQuery.validator.methods.cpf.call(this, value, element);
}
else if (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)){
return true;
} else {
this.settings.messages.documento.documento = "Informe um CPF válido.";
}
}
else if (value.length <= 14) {
if(jQuery.validator.methods.cnpj.call(this, value, element)){
return true;
} else {
this.settings.messages.documento.documento = "Informe um CNPJ válido.";
}
}
return false;
}, "Informe um documento válido.");
这篇关于jQuery Validate的自定义验证(两种方法合二为一)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!