jQuery Validate 的自定义验证(二合一)
我想知道,如何在我的方法中调用 jquery validate 的另一个自定义验证方法来验证某些数据。例如,我有一个名为“文档 ID”的字段,它可以接受 CPF 或 CNPJ(两者都是巴西文档),并且我需要使用 jquery validate 对其进行验证。我正在做这样的事情:
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!");
当我为每种类型都有一个字段时,两者都工作正常,但我只有一个字段,并且我必须发现我的用户在文本字段上输入的内容并验证它,像这样:
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)。
我该怎么做呢?以及如何更改自定义验证中的消息?
谢谢你! 干杯!
我已经在 jsbin 中发布了我的代码,如果您想查看: http://jsbin.com/ijetex/ 5/编辑
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');
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 ?
Thank you!
Cheers!
I've posted my code in jsbin, if you want to look: http://jsbin.com/ijetex/5/edit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这又如何呢?
更改错误消息的完整示例
What about this?
Full example changing the error message
如何在验证定义的范围之外创建这些函数(即不使用匿名函数)?
how about creating those function outside of the scope of the validation definition (i.e not using anonymous functions)?