function MachineName::validateMachineName
Same name in other branches
- 9 core/lib/Drupal/Core/Render/Element/MachineName.php \Drupal\Core\Render\Element\MachineName::validateMachineName()
- 8.9.x core/lib/Drupal/Core/Render/Element/MachineName.php \Drupal\Core\Render\Element\MachineName::validateMachineName()
- 10 core/lib/Drupal/Core/Render/Element/MachineName.php \Drupal\Core\Render\Element\MachineName::validateMachineName()
Form element validation handler for machine_name elements.
Note that #maxlength is validated by _form_validate() already.
This checks that the submitted value:
- Does not contain the replacement character only.
- Does not contain disallowed characters.
- Is unique; i.e., does not already exist.
- Does not exceed the maximum length (via #maxlength).
- Cannot be changed after creation (via #disabled).
File
-
core/
lib/ Drupal/ Core/ Render/ Element/ MachineName.php, line 246
Class
- MachineName
- Provides a machine name render element.
Namespace
Drupal\Core\Render\ElementCode
public static function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
// Verify that the machine name not only consists of replacement tokens.
if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
$form_state->setError($element, t('The machine-readable name must contain unique characters.'));
}
// Verify that the machine name contains no disallowed characters.
if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
if (!isset($element['#machine_name']['error'])) {
// Since a hyphen is the most common alternative replacement character,
// a corresponding validation error message is supported here.
if ($element['#machine_name']['replace'] == '-') {
$form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
}
else {
$form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
}
}
else {
$form_state->setError($element, $element['#machine_name']['error']);
}
}
// Verify that the machine name is unique. If the value matches the initial
// default value then it does not need to be validated as the machine name
// element assumes the form is editing the existing value.
$initial_values = $form_state->get('machine_name.initial_values') ?: [];
if (!array_key_exists($element['#name'], $initial_values) || $initial_values[$element['#name']] !== $element['#value']) {
$function = $element['#machine_name']['exists'];
if (call_user_func($function, $element['#value'], $element, $form_state)) {
$form_state->setError($element, t('The machine-readable name is already in use. It must be unique.'));
}
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.