@arnoldo.moen
CakePHP provides several built-in validation helpers that allow you to easily validate data in your application. Here's an example of how to use these helpers:
1 2 3 4 5 6 7 8 |
// in User.php public $validate = array( 'email' => array( 'rule' => 'email', 'required' => true, 'message' => 'Please enter a valid email address' ) ); |
This rule checks that the email field is a valid email address and is required.
1 2 3 4 5 6 7 8 9 |
// in UsersController.php public function add() { if ($this->request->is('post')) { $this->User->set($this->request->data); if ($this->User->validates()) { // save the user } } } |
Here, we're setting the data to be validated with set
, and then calling validates
to check that it meets the validation rules.
1
|
$errors = $this->User->validationErrors;
|
You can then use these errors to display feedback to the user about what went wrong.
There are many other validation helpers available in CakePHP, such as notEmpty
, numeric
, date
, and more. You can find more information on these helpers in the official CakePHP documentation.