Cakephp validate without saving ()

I am trying to use CakePHP validation without using save() . But it always returns errors. I am inserting text, but the check 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". } 
+4
source share
5 answers

In CakePHP 2.0 and CakePHP 1.3

$this->ModelName->validates(); does not accept an array of data, if you pass anything to validates() , it is an array of parameters, which is then processed using modelCallback beforeValidates()

Instead, try this logic if you want to determine if the data is valid:

 $this->ModelName->set($this->data); if ($this->ModelName->validates()) { // Data Validated } else { // Data Not Validated } 
+10
source

thats because you should not use it in this context. it must have these fields present in the $ 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 this is pretty well documented ...

+2
source

In a similar note in the CakePHP 2.0 model, there is an option to check only for saveAll ().

validate: set to false to disable validation, true to check each record before saving, โ€œfirstโ€ to check all records before they are saved (default) or โ€œonlyโ€ to check only records, but not save them.

+1
source

Everything looks great. Make sure you create one if you use the cakephp method to create the form

 <?php echo $this->Form->create("Admin"); ?> 

Here "Admin" is the name of the model.

0
source

Assign

 $this->data['ModelName']['m_subject'] = $this->data['ModelName']['m_subject']['name'] $this->data['ModelName']['m_text'] = $this->data['ModelName']['m_text']['name'] 

Because

Since loading a file is always an array, it will look like this.

  'm_subject' => array( 'name' => 'foobar', 'size' => 1234567, 'error' => 0, ... ) 

That way, he will always give you an error. Since it is looking for a string and an array found.

0
source

Source: https://habr.com/ru/post/1393361/


All Articles