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
}
}
});