class ImeiValidator

Public Instance Methods

validate_each(record, attribute, value) click to toggle source
# File lib/active_validation/validators/imei_validator.rb, line 5
def validate_each(record, attribute, value)
  return if valid?(value.to_s)

  record.errors[attribute] <<
    (options[:message] || I18n.t('active_validation.errors.messages.imei'))
end

Private Instance Methods

valid?(value) click to toggle source
# File lib/active_validation/validators/imei_validator.rb, line 36
def valid?(value)
  valid_length?(value) &&
    valid_format?(value) &&
    valid_luhn?(value)
end
valid_format?(value) click to toggle source
# File lib/active_validation/validators/imei_validator.rb, line 14
def valid_format?(value)
  value =~ /\A[\d\.\:\-\s]+\z/i
end
valid_length?(value) click to toggle source
# File lib/active_validation/validators/imei_validator.rb, line 18
def valid_length?(value)
  value.present?
end
valid_luhn?(value) click to toggle source
# File lib/active_validation/validators/imei_validator.rb, line 22
def valid_luhn?(value)
  number = value.gsub(/\D/, '').reverse

  total = 0
  number.chars.each_with_index do |chr, idx|
    result = chr.to_i
    result *= 2 if idx.odd?
    result = (1 + (result - 10)) if result >= 10
    total += result
  end

  (total % 10).zero?
end