How to 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. User can skip it and submit the form. It should not return an error because it is not required, and because they did not enter the URL. But now this is happening, due to http: //.

I heard that I can use beforeValidate () to check if it has http: // and then clear the URL field, which allows me to skip the error message.

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

Thanks.

+4
source share
2 answers

Yes, beforeValidate () is a model function. Therefore, each model has this. How should you 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 } } 
+6
source

instead of hardcoding http: // to the form, add the correct validation for the urls and use the following to resolve spaces

'allowEmpty' => true

+2
source

Source: https://habr.com/ru/post/1336836/


All Articles