2015-12-03 15:02:22 +01:00
|
|
|
class SiretFormatValidator < ActiveModel::EachValidator
|
|
|
|
def validate_each(record,attribute,value)
|
|
|
|
unless value =~ /^\d{14}$/
|
|
|
|
record.errors.add(attribute, :format)
|
|
|
|
end
|
|
|
|
unless value!= nil && (luhn_checksum(value) % 10 == 0)
|
|
|
|
record.errors.add(attribute, :checksum)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2017-06-12 15:35:21 +02:00
|
|
|
|
2015-12-03 15:02:22 +01:00
|
|
|
def luhn_checksum(value)
|
|
|
|
accum = 0
|
|
|
|
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
|
|
|
|
accum
|
|
|
|
end
|
|
|
|
end
|