class CreditCardValidator

Public Instance Methods

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

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

Private Instance Methods

valid?(value, options) click to toggle source
# File lib/active_validation/validators/credit_card_validator.rb, line 84
def valid?(value, options)
  striped_value = value.gsub(/\D/, '')

  valid_format?(value, options) &&
    valid_length?(striped_value, options) &&
    valid_prefix?(striped_value, options)
end
valid_format?(value, options) click to toggle source
# File lib/active_validation/validators/credit_card_validator.rb, line 43
def valid_format?(value, options)
  value =~ (options[:strict] ? /^[0-9]+$/ : /^[0-9 -.]+$/)
end
valid_length?(value, options) click to toggle source
# File lib/active_validation/validators/credit_card_validator.rb, line 47
def valid_length?(value, options)
  return(false) unless value.present?

  card = options[:card] || :all
  value_size = value.size

  case card
  when :amex
    LENGTHS[:american_express].include?(value_size)
  when :all
    value_size_range = LENGTHS.values.flatten.uniq.sort
    value_size.between?(value_size_range.first, value_size_range.last)
  else
    LENGTHS[card].include?(value_size)
  end
end
valid_prefix?(value, options) click to toggle source
# File lib/active_validation/validators/credit_card_validator.rb, line 64
def valid_prefix?(value, options)
  card = options[:card] || :all

  case card
  when :amex
    PREFIXES[:american_express].any? { |pat| value.start_with?(pat) }
  when :all
    result = false
    LENGTHS.each do |key, values|
      if values.include?(value.size)
        result = PREFIXES[key].any? { |pat| value.start_with?(pat) }
        break if result
      end
    end
    result
  else
    PREFIXES[card].any? { |pat| value.start_with?(pat) }
  end
end