if ($this->request->is('post')) { $validator = new Validator(); $validator->requirePresence('email') ->notEmpty('email', 'Please enter your email address.'); $errors = $validator->errors($this->request->getData()); if (empty($errors)) { // process form data } else { $this->Flash->error($validator->validationError('email')); } }
if ($this->request->is('post')) { $validator = new Validator(); $validator->add('password', [ 'complexity' => [ 'rule' => function ($value) { return preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $value); }, 'message' => 'Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number, and one special character.' ] ]); $errors = $validator->errors($this->request->getData()); if (empty($errors)) { // process form data } else { $this->Flash->error($validator->validationError('password', 'complexity')); } }In this example, a custom validation rule is created using a closure and the `add()` method. The `message` option is used to specify a custom error message for the rule. If the validation fails, the `$validator->validationError('password', 'complexity')` method is used to get the custom error message and display it to the user. Package Library: The `Validator` class is part of the CakePHP framework, a popular PHP web development framework.