Sha256: 371dd0dd7fcb07e5c2bec89448af8345a967d6a61fd2a7408d6a7b7ca2dddaef

Contents?: true

Size: 667 Bytes

Versions: 11

Compression:

Stored size: 667 Bytes

Contents

class ImeiValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s)
      record.errors[attribute] << (options[:message] || I18n.t('flash_validators.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

11 entries across 11 versions & 1 rubygems

Version Path
flash_validators-3.0.12 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.11 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.10 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.9 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.8 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.7 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.6 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.5 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.4 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.3 lib/flash_validators/validators/imei_validator.rb
flash_validators-3.0.2 lib/flash_validators/validators/imei_validator.rb