I've seen some posts on this but haven't been able to find a solution for my scenario. I've got a form that I am trying to do a check for leading and trailing spaces. The is inside a hook_form_validation_validate for Drupal using Webform Validation's API. I've used a few variations, but these are the two that seem the most logical.
foreach ($items as $key => $val) {
// @todo: Check for scenarios where $val is an array.
$valCheckSpace = preg_match('/^\s*/', $val);
if ($valCheckSpace) {
$errors[$key] = t('%item cannot have leading or trailing spaces.', array('%item' => $components[$key]['name'], '%num' => $max_length));
}
}
return $errors;
}
and this one:
foreach ($items as $key => $val) {
// @todo: Check for scenarios where $val is an array.
$valCheckSpace = preg_match('/^\s*/g', $val);
if ($valCheckSpace) {
$errors[$key] = t('%item cannot have leading or trailing spaces.', array('%item' => $components[$key]['name'], '%num' => $max_length));
}
}
return $errors;
}
Here's one more:
foreach ($items as $key => $val) {
// @todo: Check for scenarios where $val is an array.
$valCheckSpace = preg_match('/^\s/', $val);
if ($valCheckSpace) {
$errors[$key] = t('%item cannot have leading or trailing spaces.', array('%item' => $components[$key]['name'], '%num' => $max_length));
}
}
return $errors;
}
Using VSCode and XDebug, nothing fires at those breakpoints and the entry goes through when it should throw an error.
Any insight on this would be greatly appreciated.
Here is an example of the data being inputted into the form field. Form field image with entries here
The image above shows what's being entered in. There are also trailing spaces after the entries.The expected results are to throw an error to let the user know that leading or trailing spaces are not allowed.