Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom jQuery Validation .addMethod

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?

like image 780
Dirty Bird Design Avatar asked Oct 07 '10 14:10

Dirty Bird Design


1 Answers

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
        }
    }
});​
like image 169
user113716 Avatar answered Oct 14 '22 17:10

user113716