You are here

public static function CardNumber::numberIsValid in Creditfield Form Element 8

Validate callback for credit card number form fields. Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org

Parameters

$value:

Return value

bool

3 calls to CardNumber::numberIsValid()
CardNumber::validateCardNumber in src/Element/CardNumber.php
CardNumberTest::testBadNumberValidation in tests/src/Unit/Element/CardNumberTest.php
@covers ::numberIsValid @dataProvider providerInvalidCardNumbers
CardNumberTest::testGoodNumberValidation in tests/src/Unit/Element/CardNumberTest.php
@covers ::numberIsValid @dataProvider providerValidCardNumbers

File

src/Element/CardNumber.php, line 93

Class

CardNumber
Provides a one-line credit card number field form element.

Namespace

Drupal\creditfield\Element

Code

public static function numberIsValid($value) {

  // short circuit here if value is not an integer
  if (!preg_match('/^\\d+$/', $value)) {
    return FALSE;
  }

  // Set the string length and parity
  $cardnumber_length = mb_strlen($value);
  if ($cardnumber_length < 14 || $cardnumber_length > 16) {
    return FALSE;
  }
  $parity = $cardnumber_length % 2;

  // Loop through each digit and do the maths
  $total = 0;
  for ($i = 0; $i < $cardnumber_length; $i++) {
    $digit = $value[$i];

    // Multiply alternate digits by two
    if ($i % 2 == $parity) {
      $digit *= 2;

      // If the sum is two digits, add them together (in effect)
      if ($digit > 9) {
        $digit -= 9;
      }
    }

    // Total up the digits
    $total += $digit;
  }

  // If the total mod 10 equals 0, the number is valid
  return $total % 10 == 0 ? TRUE : FALSE;
}