View source
<?php
namespace Drupal\creditfield\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Render\Element;
use Drupal\Core\Form\FormStateInterface;
class CardCode extends FormElement {
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#maxlength' => 4,
'#autocomplete_route_name' => FALSE,
'#element_validate' => [
[
$class,
'validateCardCode',
],
],
'#process' => [
[
$class,
'processCardCode',
],
],
'#pre_render' => [
[
$class,
'preRenderCardCode',
],
],
'#theme' => 'input__textfield',
'#theme_wrappers' => [
'form_element',
],
];
}
public static function processCardCode(&$element, FormStateInterface $form_state, &$complete_form) {
return $element;
}
public static function validateCardCode(&$element, FormStateInterface $form_state, &$complete_form) {
if (!static::numberIsValid($element['#value'])) {
$form_state
->setError($element, t('Please enter a valid card code.'));
return;
}
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input !== FALSE && $input !== NULL) {
return str_replace([
"\r",
"\n",
], '', $input);
}
}
public static function preRenderCardCode($element) {
$element['#attributes']['type'] = 'text';
Element::setAttributes($element, [
'id',
'name',
'value',
'size',
'maxlength',
'placeholder',
]);
static::setAttributes($element, [
'form-text',
]);
return $element;
}
public static function numberIsValid($value) {
return (bool) preg_match('/^\\d{3,4}$/', $value);
}
}