silverstripe-framework/forms/CreditCardField.php
Sean Harvey 9f3344b355 API CHANGE Removed built-in behaviour.js client-side form validation.
This is no longer supported. Please use custom client-side validation instead. (see 3.0.0 changelog
for more information)
2012-03-09 12:19:57 +13:00

66 lines
2.3 KiB
PHP

<?php
/**
* CreditCard field, contains validation and formspec for creditcard fields.
* @package forms
* @subpackage fields-formattedinput
*/
class CreditCardField extends TextField {
function Field() {
$parts = explode("\n", chunk_split($this->value,4,"\n"));
$parts = array_pad($parts, 4, "");
// TODO Mark as disabled/readonly
$field = "<span id=\"{$this->name}_Holder\" class=\"creditCardField\">" .
"<input autocomplete=\"off\" name=\"{$this->name}[0]\" value=\"$parts[0]\" maxlength=\"4\"" . $this->getTabIndexHTML(0) . " /> - " .
"<input autocomplete=\"off\" name=\"{$this->name}[1]\" value=\"$parts[1]\" maxlength=\"4\"" . $this->getTabIndexHTML(1) . " /> - " .
"<input autocomplete=\"off\" name=\"{$this->name}[2]\" value=\"$parts[2]\" maxlength=\"4\"" . $this->getTabIndexHTML(2) . " /> - " .
"<input autocomplete=\"off\" name=\"{$this->name}[3]\" value=\"$parts[3]\" maxlength=\"4\"" . $this->getTabIndexHTML(3) . " /></span>";
return $field;
}
/**
* Get tabindex HTML string
*
* @param int $increment Increase current tabindex by this value
* @return string
*/
protected function getTabIndexHTML($increment = 0) {
$tabIndex = (int)$this->getTabIndex() + (int)$increment;
return (is_numeric($tabIndex)) ? ' tabindex = "' . $tabIndex . '"' : '';
}
function dataValue() {
if(is_array($this->value)) return implode("", $this->value);
else return $this->value;
}
function validate($validator){
// If the field is empty then don't return an invalidation message
if(!trim(implode("", $this->value))) return true;
$i=0;
if($this->value) foreach($this->value as $part){
if(!$part || !(strlen($part) == 4) || !preg_match("/([0-9]{4})/", $part)){
switch($i){
case 0: $number = _t('CreditCardField.FIRST', 'first'); break;
case 1: $number = _t('CreditCardField.SECOND', 'second'); break;
case 2: $number = _t('CreditCardField.THIRD', 'third'); break;
case 3: $number = _t('CreditCardField.FOURTH', 'fourth'); break;
}
$validator->validationError(
$this->name,
sprintf(
_t('Form.VALIDATIONCREDITNUMBER', "Please ensure you have entered the %s credit card number correctly."),
$number
),
"validation",
false
);
return false;
}
$i++;
}
}
}