mirror of
https://github.com/internetee/registry.git
synced 2025-07-26 04:28:27 +02:00
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:
parent
48ae6cf471
commit
52452f91bf
6 changed files with 103 additions and 34 deletions
|
@ -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
|
22
app/validators/contact/ident/national_id_validator.rb
Normal file
22
app/validators/contact/ident/national_id_validator.rb
Normal 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
|
21
app/validators/contact/ident/reg_no_validator.rb
Normal file
21
app/validators/contact/ident/reg_no_validator.rb
Normal 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
|
Loading…
Add table
Add a link
Reference in a new issue