Postcode Validation
Postcode Validation Regex
Regular Expression to match valid postcode format:
/^\s*([A-Z]{1,2}[0-9][A-Z0-9]?)\s*([0-9][ABD-HJLNP-UW-Z]{2})\s*$/i
This is according to the PAF digest as published by Royal Mail (2003).
Features:
- Leading and trailing whitespace ignored (can remove \s* from beggining and end if there is a trim() function. JS does not have one)
- OPTIONAL whitespace separating outcode and incode.
- Any separating whitespace is not pre-stripped, therefore if it is provided it can help detect invalid codes, which would by chance become valid if the space were ommited.
- Matching is case-insensitive (can remove the i flag if the case is known).
- The letters C,I,K,M,O,V never appear in the incode, and the regular expression checks this.
- The outcode and incode are reliably captured.
Shortcomings:
- If a space is not provided, and the incode is mis-typed, it may still form a valid postcode:
- Intended: A12 3BB (A123BB without space)
- Typed: A12BB (missed 3)
- Matched: A1 2BB (Valid, but different postcode)
There is no way to avoid this, it is a flaw in the design of the postcode, due to the oft-omitted space.
- Partial postcodes are not matched.
- It would be relatively easy to make the incode optional.
- Most applications requiring partial matches will have RM postcode data to hand, and can use that to match.