Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp validate without save()

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".
}
like image 866
lolalola Avatar asked Dec 12 '22 05:12

lolalola


2 Answers

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
}
like image 54
Justin Yost Avatar answered Jan 10 '23 19:01

Justin Yost


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...

like image 30
mark Avatar answered Jan 10 '23 19:01

mark