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,telandpasswordperforms server-side and client-side validation (#patternis copied onto['#attributes']['pattern']).OTOH, the
urlexample only performs client-side validation, and the outer#patternis 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