Validate uk postcodes in php

Nominet requires that the uk postcode be in a valid format, this is a routine I wrote many years ago but still works today.

Code after the break

# Main function  validate_uk_postcode($postcode)
# All code Copyright Karl Gray (c) 2000,2001
#
# It will reformat the postcode and present it in a uniform format acceptable to Nominet
# If the postcode is invalid it returns INVALID, if it is good it returns the postcode properly formated
#
# Here are the various regular expressions we have used.
#
# Our original one, Breaks on unusual london postcodes
# ^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$
#
# From nominet, no start or termination, users can enter guff at beginning or end
# [A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} [0-9][A-Z]{2}
#
# Our new one, Fixed Nominet one to prevent pre or post garbage.
# ^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} [0-9][A-Z]{2}$
# Now covers All weird london postcodes

### FUNCTIONS ###

function tidy_postcode($postcode) {
	$postcode=strtoupper($postcode);
	$postcode=trim($postcode);
	if (!eregi(" ",$postcode)) {
		$len=strlen($postcode);
		$postcode[$len]=$postcode[$len-1];
		$postcode[$len-1]=$postcode[$len-2];
		$postcode[$len-2]=$postcode[$len-3];
		$postcode[$len-3]=" ";
	}
	return ($postcode);
}

function validate_uk_postcode($postcode) {

# Reformat postcode,  space is now in right place for Nominet orders
	$postcode=tidy_postcode($postcode);

# Check if postcode is valid
	if (!eregi("^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1} [0-9][A-Z]{2}$",$postcode)) {
		return("INVALID");
	}
# YES! got one right 
	return($postcode);
}

I used RegExpBuddy to help validate the latest update to the regexp. Very handy bit of software.

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.