Skip to content

Instantly share code, notes, and snippets.

@benpickles
Forked from olly/gist:4754077
Last active December 12, 2015 09:59
Show Gist options
  • Save benpickles/4755435 to your computer and use it in GitHub Desktop.
Save benpickles/4755435 to your computer and use it in GitHub Desktop.
Regexp for validating a UK postcode.
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