demarches-normaliennes/app/validators/siret_format_validator.rb

26 lines
550 B
Ruby
Raw Normal View History

2015-12-03 15:02:22 +01:00
class SiretFormatValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if !value&.match?(/^\d{14}$/)
2015-12-03 15:02:22 +01:00
record.errors.add(attribute, :format)
end
if value.present? && (luhn_checksum(value) % 10 != 0)
2015-12-03 15:02:22 +01:00
record.errors.add(attribute, :checksum)
end
end
private
2015-12-03 15:02:22 +01:00
def luhn_checksum(value)
accum = 0
2015-12-03 15:02:22 +01:00
value.reverse.each_char.map(&:to_i).each_with_index do |digit, index|
t = index.even? ? digit : digit * 2
t = t - 9 if t >= 10
accum += t
end
2015-12-03 15:02:22 +01:00
accum
end
end