Further refactor SiretFormatValidator#validate_each
This commit is contained in:
parent
36950b985b
commit
940dfe422b
1 changed files with 10 additions and 2 deletions
|
@ -1,16 +1,24 @@
|
||||||
class SiretFormatValidator < ActiveModel::EachValidator
|
class SiretFormatValidator < ActiveModel::EachValidator
|
||||||
def validate_each(record, attribute, value)
|
def validate_each(record, attribute, value)
|
||||||
if !value&.match?(/^\d{14}$/)
|
if !format_is_valid(value)
|
||||||
record.errors.add(attribute, :format)
|
record.errors.add(attribute, :format)
|
||||||
end
|
end
|
||||||
|
|
||||||
if value.present? && (luhn_checksum(value) % 10 != 0)
|
if !luhn_passed(value)
|
||||||
record.errors.add(attribute, :checksum)
|
record.errors.add(attribute, :checksum)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
def format_is_valid(value)
|
||||||
|
value&.match?(/^\d{14}$/)
|
||||||
|
end
|
||||||
|
|
||||||
|
def luhn_passed(value)
|
||||||
|
value.present? && (luhn_checksum(value) % 10 == 0)
|
||||||
|
end
|
||||||
|
|
||||||
def luhn_checksum(value)
|
def luhn_checksum(value)
|
||||||
accum = 0
|
accum = 0
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue