Validating postcodes php
Note that this function only validates the format of a postcode and does not validate that the postcode exists; this would require access to the Royal Mail database.This function allows the characters in the postcode to be in either upper or lower case, and permits any amount of leading and trailing space and space between the first and second parts.I have tried several regexes and still some valid postal codes sometimes get rejected. While I am using regexes for any other country (except for two countries for which I can match states/provinces with the postal code), for the UK I would like something more solid and much easier to fix when something doesn't work.Searching the internet, Wikipedia and SO, I could only find regex validation solutions. Updating from Code Point periodically is not what I have in mind (it has to be done often, as to not reject valid newly assigned postcodes). [0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC)[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.is a PHP class that can validate postcode formats, extract parts of postcodes, and determine the post towns corresponding to postcodes.
But you are complicating the solution far more than you think.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.