Change record status: 
Project: 
Introduced in branch: 
8.x
Introduced in version: 
8.0-dev
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
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Not done

Comments

jonhattan’s picture

So for clarity, the above examples for textfield, tel and password 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).

Manuel Garcia’s picture

This is an undocumented property, let's fix this:
https://www.drupal.org/project/drupal/issues/2938743