View source
<?php
function creditfield_element_info() {
$types['creditfield_cardnumber'] = array(
'#input' => TRUE,
'#element_validate' => array(
'creditfield_cardnumber_validate',
),
'#autocomplete_path' => FALSE,
'#process' => array(
'form_process_creditfield',
),
'#theme' => 'textfield',
'#theme_wrappers' => array(
'form_element',
),
'#maxlength' => 16,
);
$types['creditfield_date'] = array(
'#input' => TRUE,
'#element_validate' => array(
'creditfield_date_validate',
),
'#process' => array(
'form_process_creditfield_date',
),
'#theme' => 'date',
'#theme_wrappers' => array(
'form_element',
),
);
$types['creditfield_cvv'] = array(
'#input' => TRUE,
'#element_validate' => array(
'creditfield_cvv_validate',
),
'#autocomplete_path' => FALSE,
'#process' => array(
'form_process_creditfield',
),
'#theme' => 'textfield',
'#theme_wrappers' => array(
'form_element',
),
'#maxlength' => 4,
);
return $types;
}
function creditfield_cardnumber_validate($element) {
if (!is_numeric($element['#value'])) {
form_error($element, t('Please enter a valid credit card number.'));
}
$cardnumber = preg_replace('/\\D/', '', $element['#value']);
$cardnumber_length = drupal_strlen($cardnumber);
$parity = $cardnumber_length % 2;
$total = 0;
for ($i = 0; $i < $cardnumber_length; $i++) {
$digit = $cardnumber[$i];
if ($i % 2 == $parity) {
$digit *= 2;
if ($digit > 9) {
$digit -= 9;
}
}
$total += $digit;
}
$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.'));
}
}
function creditfield_date_validate($element) {
if ($element['#value']['year'] == date('Y', time()) && $element['#value']['month'] < date('m', time())) {
form_error($element, t('Please enter a valid expiration date.'));
}
}
function creditfield_cvv_validate($element) {
if (!is_numeric($element['#value'])) {
form_error($element, t('Please enter a valid CVV number.'));
}
}
function form_process_creditfield($element) {
return $element;
}
function form_process_creditfield_date($element) {
if (empty($element['#value'])) {
$element['#value'] = array(
'month' => format_date(REQUEST_TIME, 'custom', 'n'),
'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
);
}
$element['#tree'] = TRUE;
$format = variable_get('date_format_short', 'm/Y');
$sort = array();
$sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
$sort['year'] = strpos($format, 'Y');
asort($sort);
$order = array_keys($sort);
foreach ($order as $type) {
switch ($type) {
case 'month':
$options = drupal_map_assoc(range(1, 12), 'map_month');
$title = t('Month');
break;
case 'year':
$options = drupal_map_assoc(range(date('Y', time()), date('Y', time()) + 10));
$title = t('Year');
break;
}
$element[$type] = array(
'#type' => 'select',
'#title' => $title,
'#title_display' => 'invisible',
'#value' => $element['#value'][$type],
'#attributes' => $element['#attributes'],
'#options' => $options,
);
}
return $element;
}