Search code examples
phpzipcodepostal-code

US/UK/CA Postal Code validation in PHP


Im not so good with regex. Im looking to add a validation function that will return true/false if the string entered into it is a valid US, UK, or CA zip/postal code.

US: NNNNN CA: LNL NLN UK: Lots of combinations

L = letter, N = Number

There are individual functions for US, and Canada, but I failed to come up with a single unified function to do this.


Solution

  • Take a look at Zend_Validate_Postcode from the Zend Framework:

    Zend_Validate_PostCode allows you to determine if a given value is a valid postal code. Postal codes are specific to cities, and in some locales termed ZIP codes.

    Zend_Validate_PostCode knows more than 160 different postal code formates. To select the correct format there are 2 ways. You can either use a fully qualified locale or you can set your own format manually.

    I guess you could either look at the source, or use it as a stand-alone component. It may have dependencies within the ZF, but you will certainly not need to use the entire framework just for that component. Hope that helps.