Module: BrazilianUtils::CreditCardUtils

Defined in:
lib/brazilian-utils/credit-card-utils.rb

Overview

Utilities for validating a payment card number (credit or debit) by its structure and Luhn check digit. No brand detection, issuer range lookup, expiry or CVV check is performed.

Class Method Summary collapse

Class Method Details

.is_valid(value) ⇒ Boolean Also known as: valid?

Validates a payment card number: 12 to 19 digits and a Luhn check digit.

Parameters:

  • value (String, Integer) —

    Whitespace, ., - and / are allowed anywhere between the digits; letters make it invalid. Pass a large number as a string to avoid floating-point precision loss.

Returns:

  • (Boolean) —

    A number whose digits are all the same is rejected even though it passes Luhn.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/brazilian-utils/credit-card-utils.rb', line 14

def self.is_valid(value)
  return false unless value.is_a?(String) || value.is_a?(Integer)

  raw = value.to_s.strip
  return false unless raw.match?(%r{\A[\d\s.\-/]+\z})

  digits = raw.gsub(%r{[\s.\-/]}, '')
  return false unless digits.match?(/\A\d{12,19}\z/)
  return false if digits.chars.uniq.length == 1

  luhn_valid?(digits)
end