自定义jQuery验证.addMethod [英] Custom jQuery Validation .addMethod
问题描述
我有一个表单,可以根据最小/最大长度来验证邮政编码.对于所有国家/地区,我需要将zip min设置为5位,但澳大利亚除外(必须为4). 这是我遇到的麻烦:
I have a form that validates zip codes on a min/max length basis. I need to have the zip min be 5 digits for all countries EXCEPT Australia which needs to be 4. Here is what Im having trouble with:
$.validator.addMethod(
"AusZip",
function(value, element) {
if ($("#Country").val("Aus") && ("#PostalCode").length < 4)) {
return false;
} else return true;
},
"Australian Zip Code Must Be at least 4 Digits");
然后按规则
rules: {
PostalCode: {
required: true,
minlength: 5 //for all countries except AUS
AusZip: true // for Aus
}
}
长度不是要走的路吗?
推荐答案
我假设所有验证规则都必须通过,这意味着如果长度为,则minlength
总是会失败. 4.
I'm assuming all validation rules must pass, which means that your minlength
will always fail if you have a length of 4.
此外,您在("#PostalCode").length
之前缺少$
.
此行还设置 #Country
的值.
$("#Country").val("Aus")
您要获取该值,然后将其比较与"Aus"
.
You want to get the value, and compare it to "Aus"
.
$("#Country").val() === "Aus"
尝试删除minlength
,然后更改自定义功能.
Try removing minlength
, and changing your custom function.
尝试一下:
编辑:已更改,因此您有2个验证器.
Changed so that you have 2 validators.
一个人验证该县为澳大利亚,值的长度至少为4.
One verifies that the county is Australia and the length of the value is at least 4.
另一人验证该县是否为 not 澳大利亚,且值的长度至少为5.
The other verifies that the county is not Australia and the length of the value is at least 5.
$.validator.addMethod("AusZip", function(value, element) {
var isAus = $("#Country").val() === "Aus";
if ( isAus && value.length < 4 ) {
return false;
} else return true;
}, "Australian Zip Code Must Be at least 4 Digits");
$.validator.addMethod("NonAusZip", function(value, element) {
var isNotAus = $("#Country").val() !== "Aus";
if ( isNotAus && value.length < 5 ) {
return false;
} else return true;
}, "Zip Code Must Be at least 5 Digits");
$('form').validate({
rules: {
PostalCode: {
required: true,
AusZip: true,
NonAusZip: true
}
}
});
或者,如果您不需要基于国家/地区的自定义验证消息,则可以执行以下操作:
Or if you don't need a custom validation message based on the country, you could do this:
$.validator.addMethod("GlobalZip", function(value, element) {
var isAus = $("#Country").val() === "Aus";
if ( ( isAus && value.length < 4 ) || value.length < 5 ) {
return false;
} else return true;
}, "Zip Code is not long enough");
$('form').validate({
rules: {
PostalCode: {
required: true,
GlobalZip: true
}
}
});
这篇关于自定义jQuery验证.addMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!