4

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
codemonkey613
  • 960
  • 1
  • 16
  • 26
  • What does the error say exactly? – Vesa Nieminen Jan 24 '11 at 21:03
  • It returns the validation error message, "URL is not valid". I need to clear the http:// prior to validation, after the form is submit, so cakephp skips the field as a blank. – codemonkey613 Jan 24 '11 at 21:18
  • 2
    see your prior question: http://stackoverflow.com/questions/4783872/cakephp-how-do-i-validate-url-but-ignore-if-http-or-blank – harpax Jan 25 '11 at 09:19

2 Answers2

6

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
   }
}
Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
  • 1
    rather set the var to blank than unset it .. it might be required in the validation rules. – harpax Jan 25 '11 at 09:22
2

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

'allowEmpty' => true

dogmatic69
  • 7,574
  • 4
  • 31
  • 49