Sha256: ea06a253e5af20862892af3da48429340c596bd7552bb4e21e0c8d712f9bc2f9

Contents?: true

Size: 661 Bytes

Versions: 2

Compression:

Stored size: 661 Bytes

Contents

class ImeiValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s)
      record.errors[attribute] << (options[:message] || I18n.t('yukonisuru.errors.messages.imei'))
    end
  end

  private

  def valid_format?(value)
    value =~ /\A[\d\.\:\-\s]+\z/i
  end

  def valid_luhn?(value)
    numbers = value.gsub(/\D/, '').reverse

    sum, i = 0, 0

    numbers.each_char do |ch|
      n = ch.to_i
      n *= 2 if i.odd?
      n = 1 + (n - 10) if n >= 10

      sum += n
      i   += 1
    end

    (sum % 10).zero?
  end

  def valid?(value)
    valid_format?(value) &&
    valid_luhn?(value)
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yukonisuru-1.0.0 lib/yukonisuru/validators/imei_validator.rb
yukonisuru-0.0.1 lib/yukonisuru/validators/imei_validator.rb