1

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.

developer5Urban
  • 43
  • 1
  • 12

2 Answers2

1

In your model write

public $validate = array(
    'field' => array(
        'rule' => 'notBlank',
        'message' => 'This field is required.'
    )
);

And then in your controller

$this->ModelName->set($this->request->data);

if ($this->ModelName->validates()) {
    // it validated logic
} else {
    // didn't validate logic
}
Pradeep Singh
  • 1,282
  • 2
  • 19
  • 35
0

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();
}
Pradeep Singh
  • 1,282
  • 2
  • 19
  • 35
Akshay Sharma
  • 1,042
  • 1
  • 8
  • 21