Validating UK postcodes with ActiveRecord validations
Validating UK postcodes with ActiveRecord
is pretty straightforward. I grabbed a regular expression from this blog post and made it slightly more forgiving to accept postcodes without spaces (so that it accepts both SW1 1AB and SW11AB).
Here is a version with the regular expression inline:
class Address < ActiveRecord::Base | |
attr_accessible :postcode | |
validates_format_of :postcode, :with => /^([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])\s?[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, :message => "invalid postcode" | |
end |
And here is the custom validator version:
class PostcodeValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
unless value =~ /^([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])\s?[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 | |
record.errors[attribute] << (options[:message] || "invalid postcode") | |
end | |
end | |
end |
To use the custom validator bung the file in app/validators/ and use like so:
class Address < ActiveRecord::Base | |
attr_accessible :postcode | |
validates :postcode, :postcode => true | |
end |