Link to home
Start Free TrialLog in
Avatar of rivkamak
rivkamakFlag for United States of America

asked on

jquery validation for zip or postal code

Is there a validation addon for the jquery validation that will validate the zipcode field , if it's american to require only 5 digits, but if the fields for country = 'canada', it should validate as min 6 char and lettes and numbers?
Avatar of David Favor
David Favor
Flag of United States of America image

Simple way is to write your one regular expression based validator.

Or you can use one of the many zipcode + postal code lookup APIs, if you must be correct.
Avatar of rivkamak

ASKER

But I need some sort of depend. and this isn't working.

$.validator.addMethod('regex', function(value, element, param) { 
        return this.optional(element) || 
  value.match(typeof param == 'string' ? new RegExp(param) : param); 
    },     'Please enter a value in the correct format.'); 

$("#form1").validate(
   {
       rules: {
          Zip : {
          required: true,
         regex:"(/\d{5}-\d{4}$|^\d{5}$/)"  
//OR 
      /* regex: {
        
        param: "(/\d{5}-\d{4}$|^\d{5}$/)",
        depends: function(element) {
          return $("#Country").val()=='USA' ;
        }
      }*/
         
             
      } // end zip
   } , //end rules
             .....

Open in new window

Hi,

Note american can be 5 or 9 digit (ZIP+4) code

I'm using this input mask http://github.com/RobinHerbots/jquery.inputmask
This is great because it allow more than one pattern and won't depend of country selection.
(you can validate server side instead)

with regex
$("#zipcode").inputmask(["99999[-9999]" , "A9A 9A9" ]); //USA or Canadian Zip Code

Open in new window


And I validate using server side using PHP

First I keep only digits and letters
preg_replace('/[^a-zA-Z0-9]/', '', $zipcode); 

Open in new window


And I validate with regex
!preg_match ('/^[A-Za-z]\d[A-Za-z]\d[A-Za-z]\d$|^([0-9]{5})([0-9]{4})?$/i', $zipcode)

Open in new window

Is there a way to integrate it in to the jquery validation system? 
ASKER CERTIFIED SOLUTION
Avatar of lenamtl
lenamtl
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial