In this final installment of the postal code trilogy, we turn our attention to the United Kingdom. Postal codes in the UK are called postcodes. They are similar to postal codes in Canada in that they contain both letters and numbers, but unlike Canadian postal codes, they are variable in length.
A postcode can have any of the following formats:
- A9 9AA
- A99 9AA
- A9A 9AA
- AA9 9AA
- AA99 9AA
- AA9A 9AA
To match all of these formats, we'll use the following regular expression: [A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}
. You may notice that, like Canadian postal codes, certain letters are only allowed in certain positions, or not at all.
There are also a few special cases that are valid postcodes but deviate from the regular format:
- Girobank -
(GIR\ 0AA)
- Father Christmas -
(SAN\ TA1)
- British Forces Post Office -
(BFPO\ (C\/O\ )?[0-9]{1,4})
- Overseas territories -
((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ)
ASP
function isValidPostCode(postCode)
dim regEx
set regEx = new RegExp
with regEx
.IgnoreCase = true
.Global = true
.Pattern = "^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$"
end with
if regEx.Test(trim(CStr(postCode))) then
isValidPostCode = true
else
isValidPostCode = false
end if
set regEx = nothing
end function
PHP
function isValidPostCode($postCode)
{
$pattern = "/^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$/i";
return (preg_match($pattern, trim($postCode)) > 0) ? true : false;
}
No comments:
Post a Comment