Improve contact ident validation

- Make country-specific national id and reg. no validations fully
extendable
- Fix wrong error type for reg. no validator

#569
This commit is contained in:
Artur Beljajev 2017-09-11 17:05:03 +03:00
parent 48ae6cf471
commit 52452f91bf
6 changed files with 103 additions and 34 deletions

View file

@ -1,30 +0,0 @@
class Contact::Ident::CodeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless record.country_code == 'EE'
if record.national_id? && !valid_national_id_ee?(value)
record.errors.add(attribute,
:invalid_national_id,
country: record.country)
end
if record.reg_no?
validator = ActiveModel::Validations::
FormatValidator.new(with: reg_no_ee_format,
attributes: attribute,
message: :invalid_reg_no,
country: record.country)
validator.validate(record)
end
end
private
def reg_no_ee_format
/\A[0-9]{8}\z/
end
def valid_national_id_ee?(ident)
Isikukood.new(ident).valid?
end
end

View file

@ -0,0 +1,22 @@
class Contact::Ident::NationalIDValidator < ActiveModel::EachValidator
def self.country_specific_validations
{
Country.new('EE') => proc { |code| Isikukood.new(code).valid? },
}
end
def validate_each(record, attribute, value)
validation = validation_for(record.country)
return unless validation
valid = validation.call(value)
record.errors.add(attribute, :invalid_national_id, country: record.country) unless valid
end
private
def validation_for(country)
self.class.country_specific_validations[country]
end
end

View file

@ -0,0 +1,21 @@
class Contact::Ident::RegNoValidator < ActiveModel::EachValidator
def self.country_specific_formats
{
Country.new('EE') => /\A[0-9]{8}\z/,
}
end
def validate_each(record, attribute, value)
format = format_for(record.country)
return unless format
record.errors.add(attribute, :invalid_reg_no, country: record.country) unless value =~ format
end
private
def format_for(country)
self.class.country_specific_formats[country]
end
end