Skip to content

Commit

Permalink
Validate format of UK postcodes (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
irisfaraway committed Feb 15, 2018
1 parent 0d82444 commit bb8a9d3
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 8 deletions.
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ gem "rest-client", "~> 2.0"

gem "secure_headers", "~> 5.0"

gem "uk_postcode", require: false

group :development, :test do
# Call "byebug" anywhere in the code to stop execution and get a debugger console
gem "byebug"
Expand Down
3 changes: 2 additions & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ GEM
thread_safe (~> 0.1)
uglifier (4.1.6)
execjs (>= 0.3.0, < 3)
uk_postcode (2.1.2)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.5)
Expand Down Expand Up @@ -285,11 +286,11 @@ DEPENDENCIES
spring
turbolinks
uglifier (>= 1.3.0)
uk_postcode
vcr (~> 4.0)
web-console (~> 2.0)
webmock (~> 3.3)


RUBY VERSION
ruby 2.4.2p198

Expand Down
10 changes: 6 additions & 4 deletions app/validators/temp_postcode_validator.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
require "uk_postcode"

class TempPostcodeValidator < ActiveModel::Validator
def validate(record)
postcode_returns_results?(record) if value_is_present?(record) && value_is_valid_length?(record)
postcode_returns_results?(record) if value_is_present?(record) && value_uses_correct_format?(record)
end

private
Expand All @@ -11,9 +13,9 @@ def value_is_present?(record)
false
end

def value_is_valid_length?(record)
return true if record.temp_postcode.length < 11
record.errors.add(:temp_postcode, :too_long)
def value_uses_correct_format?(record)
return true if UKPostcode.parse(record.temp_postcode).full_valid?
record.errors.add(:temp_postcode, :wrong_format)
false
end

Expand Down
2 changes: 1 addition & 1 deletion config/locales/forms/company_postcode_forms/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ en:
attributes:
temp_postcode:
blank: "Enter a postcode"
too_long: "Enter a valid UK postcode"
wrong_format: "Enter a valid UK postcode"
no_results: "We couldn't find any addresses for that postcode. Check the postcode or enter the address manually."
os_places_error: "Our address finder isn't working."
reg_identifier:
Expand Down
4 changes: 2 additions & 2 deletions spec/forms/company_postcode_forms_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@
end
end

context "when a company_postcode is too long" do
context "when a company_postcode is in the wrong format" do
before(:each) do
company_postcode_form.temp_postcode = "ABC123DEF567"
company_postcode_form.temp_postcode = "foo"
end

it "is not valid" do
Expand Down

0 comments on commit bb8a9d3

Please sign in to comment.