diff --git a/app/models/applicants/personal_detail.rb b/app/models/applicants/personal_detail.rb index 2f381a3d..418abf59 100644 --- a/app/models/applicants/personal_detail.rb +++ b/app/models/applicants/personal_detail.rb @@ -19,7 +19,8 @@ class PersonalDetail validate :age_less_than_maximum validate :minimum_age validates :sex, presence: true, inclusion: { in: SEX_OPTIONS } - validates :passport_number, presence: true + validates :passport_number, presence: true, length: { maximum: 20, message: "passport number is invalid" } + validate :valid_passport_number validates :nationality, presence: true, inclusion: { in: NATIONALITIES } validates :address_line_1, presence: true validates :city, presence: true @@ -91,6 +92,21 @@ def age_less_than_maximum errors.add(:date_of_birth) end + def valid_passport_number + return if passport_number.blank? + + # Reject if it contains any characters other than alphanumeric + unless passport_number =~ /\A[a-zA-Z0-9]+\z/ + errors.add(:passport_number, 'passport number is invalid') + return + end + + # Reject if it doesn't contain at least one number + unless passport_number =~ /\d/ + errors.add(:passport_number, 'passport number is invalid') + end + end + def minimum_age # rubocop:disable Rails/Blank return unless date_of_birth.present? diff --git a/spec/models/applicants/personal_detail_spec.rb b/spec/models/applicants/personal_detail_spec.rb index 14d719b0..d8621985 100644 --- a/spec/models/applicants/personal_detail_spec.rb +++ b/spec/models/applicants/personal_detail_spec.rb @@ -190,6 +190,36 @@ module Applicants end end end + + describe "passport_number validations" do + subject(:model) { described_class.new(passport_number:) } + + before { model.valid? } + + context "when passport_number is valid" do + valid_passports = %w[PAT34566 A345667 JS3445 434455AFT 2453454] + + valid_passports.each do |valid_passport| + let(:passport_number) { valid_passport } + + it "#{valid_passport} should be valid" do + expect(model.errors.messages_for(:passport_number)).to be_blank + end + end + end + + context "when passport_number is invalid" do + invalid_passports = ["asdfasdf", "nil", "%$^%%^%"] + + invalid_passports.each do |invalid_passport| + let(:passport_number) { invalid_passport } + + it "#{invalid_passport} should be invalid" do + expect(model.errors.messages_for(:passport_number)).to include("passport number is invalid") + end + end + end + end end end end