You are here

function creditfield_cardnumber_validate in Creditfield Form Element 7

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

Parameters

array $element:

1 string reference to 'creditfield_cardnumber_validate'
creditfield_element_info in ./creditfield.module
Implements hook_element_info().

File

./creditfield.module, line 48

Code

function creditfield_cardnumber_validate($element) {
  if (!is_numeric($element['#value'])) {
    form_error($element, t('Please enter a valid credit card number.'));
  }

  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  $cardnumber = preg_replace('/\\D/', '', $element['#value']);

  // Set the string length and parity
  $cardnumber_length = drupal_strlen($cardnumber);
  $parity = $cardnumber_length % 2;

  // Loop through each digit and do the maths
  $total = 0;
  for ($i = 0; $i < $cardnumber_length; $i++) {
    $digit = $cardnumber[$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
  $valid = $total % 10 == 0 ? TRUE : FALSE;
  if (!$valid) {
    form_error($element, t('Your card appears to be invalid. Please check the numbers and try again.'));
  }
}