Sha256: 8061b0e2871f35f57dded439d3636a1974f27e49f12b6cdf49974f27a9447021
Contents?: true
Size: 781 Bytes
Versions: 3
Compression:
Stored size: 781 Bytes
Contents
class ImeiValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless valid?(value.to_s, options) record.errors[attribute] << (options[:message] || I18n.t('errors.messages.imei')) end end private def self.validate_format(imei_number) !!(imei_number =~ /\A[\d\.\:\-\s]+\z/i) # 356843052637512 or 35-6843052-637512 or 35.6843052.637512 end def self.luhn_valid?(input) numbers = input.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?(imei, options) self.class.validate_format(imei) \ && self.class.luhn_valid?(imei) end end
Version data entries
3 entries across 3 versions & 1 rubygems