I'm trying to use CakePHP validation without using save()
.
But it always returns errors. I insert text, but validation says it is empty. Why?
My Model:
var $validate = array(
'm_subject' => array(
'empty' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Subject is empty',
)
),
'm_text' => array(
'empty' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Text is empty',
)
)
);
In my Controller:
$this->Admin->set($this->data);
if($this->Admin->validates($this->data, array('m_subject', 'm_text'))) {
//OK
}
else {
$errors = $this->Admin->invalidFields();
pr($errors); //Always returns "Subject is empty" and "Text is empty".
}
In both CakePHP 2.0 and CakePHP 1.3
$this->ModelName->validates();
does not take an array of data if you are passing anything to validates()
it is an array of options that is then processed by the modelCallback beforeValidates()
Instead try this logic if you wish to determine if data is valid:
$this->ModelName->set($this->data);
if ($this->ModelName->validates()) {
// Data Validated
} else {
// Data Not Validated
}
thats because you shouldnt use required in this context. it needs to have those fields present in $this->data otherwise.
read the part about it here: http://www.dereuromark.de/2010/09/21/saving-model-data-and-security/
oh, now i see the problem. you are using validates() incorrectly! you need to set the data first:
$this->User->set($this->data);
$res = $this->User->validates();
but thats pretty good documented...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With