I wish to validate in controller in cakephp. Though my validations are working well in Models but instead of model I wish to validate it in controller as well.
What I did to validate in contrller.
$validates = array('email' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
),
'isUnique' => array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
),
'email' => array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
)
));
if ($this->User->validates($validates)) {
die("Action can be performed as validated !! Fields are correct");
} else {
die("Action can't be performed !! Fields are in-correct");
}
It always end me in correct condition no matters if field is correct or not. Please help
Setting $this->Model->validates = $validates; will work for you as suggested in the previous answer but you risk overwriting all other validation rules which may be set in the Model. It's much better to add, modify and remove validation rules on the fly like such:
$this->Model->validator()
->add('email', 'required', array(
'rule' => array('notEmpty'),
'message' => 'A email is required'
))
->add('email', 'isUnique', array(
'rule' => array('notEmpty'),
'message' => 'This email is already registered'
))
->add('email', 'email', array(
'rule' => array('email'),
'message' => 'Enter valid mail address'
));
I left your array exactly as you presented it, however I assume you have the wrong rule on isUnique
You can read more about binding rules here: http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules