Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 PST on 31 March 2024, to get $100 off your ticket.
By jibran on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Introduced in version:
8.0-dev
Issue links:
Description:
textfield
, tel
, email
, url
and password
now support '#pattern'
FAPI property to provide easy validation for Form API fields. Browsers could also use this property to perform client-side validation, but you can ensure it is performed server-side as well.
/**
* Builds a simple form using the FAPI #pattern property.
*/
function form_test_pattern_form($form, &$form_state) {
$form['textfield'] = array(
'#type' => 'textfield',
'#title' => 'One digit followed by lowercase letters',
'#pattern' => '[0-9][a-z]+',
);
$form['tel'] = array(
'#type' => 'tel',
'#title' => 'Everything except numbers',
'#pattern' => '[^\d]*',
);
$form['password'] = array(
'#type' => 'password',
'#title' => 'Password',
'#pattern' => '[01]+',
);
$form['url'] = array(
'#type' => 'url',
'#title' => 'Client side validation',
'#description' => 'Just client side validation, using the #pattern attribute.',
'#attributes' => array(
'pattern' => '.*foo.*',
),
'#pattern' => 'ignored',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
Impacts:
Module developers
Comments
server or client side?
So for clarity, the above examples for
textfield
,tel
andpassword
performs server-side and client-side validation (#pattern
is copied onto['#attributes']['pattern']
).OTOH, the
url
example only performs client-side validation, and the outer#pattern
is ignored.So, you're not getting server-side validation when using
$form['foo']['#attributes']['pattern'] = '/something/';
in despite you also add an outer#pattern
, unless you enforce it with$form['foo']['#element_validate'][] = array(get_called_class(), 'validatePattern');
(untested).This is an undocumented
This is an undocumented property, let's fix this:
https://www.drupal.org/project/drupal/issues/2938743