Custom jQuery Validation .addMethod question -


i have form validates zip codes on min/max length basis. need have zip min 5 digits countries except australia needs 4. here 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 @ least 4 digits"     ); 

then in rules

rules: {     postalcode: {     required: true,     minlength: 5 //for countries except aus     auszip: true // aus     } } 

is length not way go?

i'm assuming all validation rules must pass, means minlength fail if have length of 4.

also, you're missing $ before ("#postalcode").length.

also line sets value of #country.

$("#country").val("aus") 

you want get value, , compare "aus".

$("#country").val() === "aus" 

try removing minlength, , changing custom function.

try this:

edit: changed have 2 validators.

one verifies county australia and length of value @ least 4.

the other verifies county not australia , length of value @ 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 @ 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 @ least 5 digits");   $('form').validate({     rules: {         postalcode: {             required: true,             auszip: true,             nonauszip: true         }     } });​ 

or if don't need custom validation message based on country, 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 not long enough");  $('form').validate({     rules: {         postalcode: {             required: true,             globalzip: true         }     } });​ 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -