Form API
The Mask Field module provides a Form API property (#mask) to mask elements in custom forms. Currently, this property is available for textifield and tel element types only, but it can be easily extended for other element types using the Drupal\mask\Helper\ElementHelper class. More often you'd just have to implement hook_element_info_alter() to enable the #mask property on another element type - check out mask_element_info_alter() for an example. Please send us a patch if you write some code to support another Drupal Core's element type.
The #mask property must be an associative array with at least the value option provided. These are the available options:
- value: A string representing the mask value. For example: "(000) 000-0000" for US phone numbers.
- reverse: A boolean indicating that the mask should be applied backward (from right to left).
- clearifnotmatch: A boolean indicating that the field should be cleared if the mask in incomplete on submission (the user did not finish the input).
- selectonfocus: A boolean indicating that the field's content should be selected when it is focused.
Example:
$form['ip'] = [
'#type' => 'textfield',
'#title' => t('IP address'),
'#mask' => [
'value' => '099.099.099.099',
'reverse' => FALSE,
'selectonfocus' => FALSE,
'clearifnotmatch' => TRUE,
],
];Please refer to the jQuery Mask Plugin documentation for more information on how to write your field's mask.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion