You are here

public static function TextBase::validatePattern in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformElement/TextBase.php \Drupal\webform\Plugin\WebformElement\TextBase::validatePattern()

Form API callback. Validate unicode pattern and display a custom error.

See also

https://www.drupal.org/project/drupal/issues/2633550

File

src/Plugin/WebformElement/TextBase.php, line 297

Class

TextBase
Provides a base 'text' (field) class.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public static function validatePattern(&$element, FormStateInterface $form_state, &$complete_form) {
  if ($element['#value'] !== '') {

    // PHP: Convert JavaScript-escaped Unicode characters to PCRE
    // escape sequence format.
    // @see https://bytefreaks.net/programming-2/php-programming-2/php-convert-javascript-escaped-unicode-characters-to-html-hex-references˚
    $pcre_pattern = preg_replace('/\\\\u([a-fA-F0-9]{4})/', '\\x{\\1}', $element['#pattern']);
    $pattern = '{^(?:' . $pcre_pattern . ')$}u';
    if (!preg_match($pattern, $element['#value'])) {
      if (!empty($element['#pattern_error'])) {
        $form_state
          ->setError($element, WebformHtmlHelper::toHtmlMarkup($element['#pattern_error']));
      }
      else {
        $form_state
          ->setError($element, t('%name field is not in the right format.', [
          '%name' => $element['#title'],
        ]));
      }
    }
  }
}