Validation rule to NOT ALLOW whitespace in string

Hi everybody, does anybody knows if there is a validation rule which does not allow a whitespace in a string in a field?

Thank you very much!

There isn’t one, but you can create a custom check

https://book.cakephp.org/4/en/orm/validation.html#creating-custom-re-usable-rules

Thnak you for your hint. Nevertheless, I absolutely do not understand what’s written here:

Please can anybody recommend me where can I find explained examples how to build my rule? Please can anyone explain me the example from cookbook?

Thnak you!

There’s examples of four ways to build your own rules here.

Here is a simple example. Note the validation name is called positiveNumber. You can easily do a preg-match for white-spaces here.

// in Model/Table/UsersTable.php
$validator->add( 'age', 'custom', [
	'rule' => [$this, 'positiveNumber'],
	'message' => 'Number cannot be negative.'
]);

public function positiveNumber($value,$context): bool
{
  if( $value < 0 ) return false;
  return true;
}
1 Like