[Drupal] How to validate a regular expression in Drupal

| | 1 min read

Consider a case where you want to enter regular expression and validate it. Here I will show you how to write a validation function. For example consider YOURMODULE_admin_settings_validate function

In my example I am using a form and a submit button.From $form_state array you can get the input value after submit. You need this value to match with the string. See the code below.


function YOURMODULE_admin_settings_validate($form, &$form_state) {
  global $_disable_messages_error, $_disable_messages_error_no;
  $pattern = $form_state['values']['name_of_your_field'];
  $pattern = preg_replace(array('/^\s*/', '/\s*$/'), '', $pattern);
  
  // Override drupal error handler to handle the preg error here
  set_error_handler('_disable_messages_error_handler');
  try {
    preg_match('/' . $pattern . '/', "This is a test string");
  }
  catch (Exception $e) {     
  }
  if ($_disable_messages_error) {
    form_set_error('','You have entered an invalid regular expression.');
    restore_error_handler();
    return;
  }
}

Here I am using an user defined error handler function. In the above code I did not write anything in the catch clause because here I am using another variable to handle the form set error.


/**
 * Custom error handler to catch the preg error while validating the regular expressions.
 */
function _disable_messages_error_handler($errno, $errstr, $errfile, $errline) {
 global $_disable_messages_error, $_disable_messages_error_no;
 $_disable_messages_error = $errstr;
 $_disable_messages_error_no = $errno;
 // Don't do anything other than set the error string.
}

Use appropriate submit and form hooks.I hope this will fix your problem too. Thank you! :)