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");
then in the rules
rules: {
PostalCode: {
required: true,
minlength: 5 //for all countries except AUS
AusZip: true // for Aus
}
}
Is length not the way to go?
I'm assuming all validation rules must pass, which means that your minlength
will always fail if you have a length of 4.
Also, you're missing a $
before ("#PostalCode").length
.
Also this line sets the value of #Country
.
$("#Country").val("Aus")
You want to get the value, and compare it to "Aus"
.
$("#Country").val() === "Aus"
Try removing minlength
, and changing your custom function.
Try this:
EDIT: Changed so that you have 2 validators.
One verifies that the county is Australia and the length of the value is at least 4.
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
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With