CakePHP validation rule automatically adding a required attribute to the field

CSamp picture CSamp · Apr 27, 2013 · Viewed 15.4k times · Source

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

Answer

obsirdian picture obsirdian · Apr 27, 2013

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.