Validating postcodes php

I came across this function a while ago in a project, but as it wasn't attributed to anyone I assumed that it was written by another coder on the same project.It was nice to track down the original author and give them the credit.Creating a function to validate UK postcodes would seem like a simple task, but there is a little more to it than checking the number of characters.

Is there a validation method which does not use regex? I supose the easiest would be to compare against a postal code database, yet that would need to be maintained and updated periodically from a reliable source. A more permissive general rule is better suited to my particular needs.

Edit: To help future visitors and keep you from posting any more regexes, here's a regex which I have tested (as of 2013-04-24) to work for all postal codes in Code Point (see @Mikkel Løkke's answer): //PHP PCRE (it was on Wikipedia, it isn't there anymore; I might have modified it, don't remember). While the above mentioned regex accomplishes this, it is not easy to update or port it.

I'd hate my code to unexpectedly break due to a valid bug fix.

I can easy work around this worry though by simply creating my own extension of Zend_Validate_Post Code, so that's what I did: library/App/Validate/Post Code.php: And of course, with the benefit of ZF's plugin loader system, once I'm happy that the bug is fixed in Zend_Validate_Post Code, I'll be able to just remove my override and Zend_Form will carry on working.

The database is only required for the get Post Town function.

You should periodically update your copy of the database to the latest version.

[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9])[0-9][ABD-HJLNP-UW-Z])$/i", $str Postal Code); Regexes are hard to debug, hard to port from one regex flavor to another (silent "errors"), and hard to update.

I am starting to think it would be better to start from the data provided by Code Point (see mikkel lokke's answer) (besides the postal codes, Code Point explains the area codes and such)check_uk_postcode('AE3A 6AR').''; // valid echo check_uk_postcode('Z9 9BA').''; // valid echo check_uk_postcode('AE3A6AR').''; // valid echo check_uk_postcode('EE34 6FR').''; // valid echo check_uk_postcode('A23A 7AR').''; // invalid echo check_uk_postcode('A23A 7AR').''; // invalid echo check_uk_postcode('WA3334E').''; // invalid echo check_uk_postcode('A2 AAR').''; // invalid I've built London only postcode based apps using the postcodes I got from HERE.

The United Kingdom postcode database is owned by the Royal Mail, who charge high fees for licences.

Tags: , ,