How do I use beforeValidate() in CakePHP?

codemonkey613 picture codemonkey613 · Jan 24, 2011 · Viewed 7.7k times · Source

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.

Answer

Nik Chankov picture Nik Chankov · Jan 25, 2011

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
   }
}