-
-
Save benpickles/4755435 to your computer and use it in GitHub Desktop.
Regexp for validating a UK postcode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rspec/autorun' | |
ValidUKPostcode = /\A( | |
[A-PR-UWYZ]\d{1,2} \s? \d[ABD-HJLNP-UWXYZ]{2}| # A9 9AA or A99 9AA | |
[A-PR-UWYZ][A-HK-Y]\d{1,2} \s? \d[ABD-HJLNP-UWXYZ]{2}| # AA9 9AA or AA99 9AA | |
[A-PR-UWYZ]\d[A-HJKSTUW] \s? \d[ABD-HJLNP-UWXYZ]{2}| # A9A 9AA | |
[A-PR-UWYZ][A-HK-Y]\d[ABEHMNPRVWXY] \s? \d[ABD-HJLNP-UWXYZ]{2}| # AA9A 9AA | |
GIR \s? 0AA | |
)\z/ix | |
describe ValidUKPostcode do | |
# http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom | |
[ | |
'EC1A 1BB', | |
'W1A 1HQ', | |
'M1 1AA', | |
'B33 8TH', | |
'CR2 6XH', | |
'DN55 1PT' | |
].each do |valid_postcode| | |
it { should match(valid_postcode) } | |
end | |
[ | |
'123 456', | |
'ABC DEF', | |
'M1 1AA1' | |
].each do |invalid_postcode| | |
it { should_not match(invalid_postcode) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment