Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP validation rule automatically adding a required attribute to the field

I am using a custom validation rule in CakePHP to be sure a value is entered into a field when a corresponding checkbox is marked:

When the "Purchasing TV" checkbox is marked, there needs to be a value in the "Enter TV Price" field.

Here's the validation rule within my model's validation array...

'tv_price'=>array(        
    'check'=>array(
        'rule'=>array('check_for_tv_price'),
        'message'=>'Please enter the television pricing information.',
    ),
)

...and here's my really simple custom validation function:

public function check_for_tv_price($check) {
    if($this->data['Client']['tv']==1&&$this->data['Client']['tv_price']=="") {
        return false;
    }
    if($this->data['Client']['tv']==1&&$this->data['Client']['tv_price']!="") {
        return true;
    }
    if($this->data['Client']['tv']==0) {
        return true;
    }

}

I've tried adding 'required'=>false and 'allowEmpty'=>true at different points in the validation array for my tv_price field, but they always override my custom rule! As a result, a user can not submit the form because the browser prevents it (due to the required attribute).

For reference, the browser spits out the following HTML:

<input id="ClientTvPrice" type="text" required="required" maxlength="255" minyear="2013" maxyear="2018" name="data[Client][tv_price]"></input>

(Note the minyear and maxyear attributes are from the form defaults.)

Has anyone found a way to prevent the automatic insertion of the required attribute when using custom validation rules?

Any guidance would be much appreciated.

Thanks!

Chris

like image 784
CSamp Avatar asked Apr 26 '13 23:04

CSamp


2 Answers

Set required to false and allowEmpty to true, that should do it for you.

'tv_price'=>array(        
    'check'=>array(
        'rule'=>array('check_for_tv_price'),
        'message'=>'Please enter the television pricing information.',
        'required' => false,
        'allowEmpty' => true
    ),
)

Hope this helps.

like image 92
obsirdian Avatar answered Oct 08 '22 01:10

obsirdian


These seems like 2.3's new HTML5 magic stuff.

Try adding 'formnovalidate' => true to the $this->FormHelper->input() options in the view.

ref:
http://book.cakephp.org/2.0/en/appendices/2-3-migration-guide.html#formhelper
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::input

like image 45
Costa Avatar answered Oct 08 '22 01:10

Costa