Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use beforeValidate() in CakePHP?

I have a form with a URL field. The default value for this field is: http://. But the field is not required. The user can skip it and submit the form. It shouldn't return an error because it's not required and because they didn't enter a URL. But right now it does, because of the http://.

I heard I can use beforeValidate() to check if it's http://, and then clear the URL field, allowing me to skip the error message.

But I don't know how to use beforeValidate(). I searched Google, but I did not find any working examples. Where do I place the code for beforeValidate()? Is it a function? How do I access the submitted form data from there?

Thanks.

like image 221
codemonkey613 Avatar asked Feb 25 '23 07:02

codemonkey613


2 Answers

Yes, beforeValidate() is a function of the model. So every model has it. How you should use it:

class YourModel extends AppModel {
   function beforeValidate(){
      if($this->data['YourModel']['url_field'] == 'http://'){
         unset($this->data['YourModel']['url_field']);
      }
      return true; //this is required, otherwise validation will always fail
   }
}
like image 200
Nik Chankov Avatar answered Mar 06 '23 18:03

Nik Chankov


instead of hard coding http:// into the form, add proper validation for urls and use the following to allow blanks

'allowEmpty' => true

like image 29
dogmatic69 Avatar answered Mar 06 '23 18:03

dogmatic69