the data validation is always return true in cakephp

250 Views Asked by At

the data validation in my User Model always return true. Can anybody tell me why? The Model: user.php

class User extends AppModel {

var $name = "User";

public $validate = array(

    "username" => array(
        "rule" => "notBlank",
        "message" => "Please enter title !",
    ),
    "password" => array(
        "rule" => "notBlank", // tập luật là không rỗng
        "message" => "Please enter info !", // thông báo khi có lỗi
    ));


}

UsersController:

if(($this->request->is('post'))) {

        $this->loadModel('User');
        $this->User->set($this->data);
        echo "</br> vao ".$this->User->validates();
        if($this->User->validates()){
            echo "</br>".$this->User->validates();
            $this->Session->setFlash("Data is avaliable !");

        }else{
            $error = $this->User->validationErrors;
            $this->Session->setFlash("Data is mot avaliable !");
            echo"not validate";
        }

But return is alway is true.

I tried to run cakephp 2..7.2 and 2.6.0 but the result is still the same.

1

There are 1 best solutions below

3
On

In CakePHP 2.x the request/form data is accessed via $this->request->data not $this->data. So you need to change the line where you set the model's data using $this->User->set() to use $this->request->data:-

if ($this->request->is('post')) {
        $this->User->set($this->request->data);
        if ($this->User->validates()){
            $this->Session->setFlash("Data is avaliable !");
        } else{
            $this->Session->setFlash("Data is not avaliable !");
        }
}

As long as you're sticking to CakePHP conventions there is no need to load the User model in the UsersController as it should be auto-loaded. So you can remove $this->loadModel('User').

If you're using the notBlank validation rule make sure you are using CakePHP 2.7 as this rule does not exist in earlier versions of Cake. For CakePHP 2.6 use the notEmpty rule.