Search code examples
cakephpcakephp-2.8

How do form validation in Cakephp?


I have been trying to do form validation in cakephp. I have a dropdown menu and I want to set it to required to allow the selection of the item in the dropdown menu first before moving to the next page. However, I am unable to do so.

I would like to know how to do form validation. I read that cakephp 2.4 and above have problem on form validation and mine is cakephp 2.8.

Please explain if should do it in the controller or model?

I have read the cookbook but wasn't help. Still new with the framework, appreciate if someone can help out.


Solution

  • Put it in your controller.php

    function add(){
        if(!empty($this->data)){
            $this->{$this->modelClass}->set($this->data);
            if($this->{$this->modelClass}->addValidate()){
    
            }
        }
    } 
    

    Put it in your model.php

    function addValidate(){
       $validate1   = array(
          'field_name' => array(
              'rule1' => array(
                  'rule' => 'notEmpty',
                  'message' => 'Please enter field_name'
               )
           )
       );
       $this->validate = $validate1;
       return $this->validates();
    }