CakePHP验证规则自动向字段添加必需属性

CSa*_*amp 5 cakephp cakephp-2.0 cakephp-2.1 cakephp-2.2

我在CakePHP中使用自定义验证规则,以确保在标记相应的复选框时将值输入到字段中:

选中

这是我模型验证数组中的验证规则......

'tv_price'=>array(        
    'check'=>array(
        'rule'=>array('check_for_tv_price'),
        'message'=>'Please enter the television pricing information.',
    ),
)
Run Code Online (Sandbox Code Playgroud)

...这是我非常简单的自定义验证功能:

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

}
Run Code Online (Sandbox Code Playgroud)

我已经尝试添加'required'=>false'allowEmpty'=>true在验证阵列我在不同的分tv_price领域,但他们总是忽略我的自定义规则!因此,用户无法提交表单,因为浏览器会阻止它(由于必需的属性).

作为参考,浏览器会吐出以下HTML:

<input id="ClientTvPrice" type="text" required="required" maxlength="255" minyear="2013" maxyear="2018" name="data[Client][tv_price]"></input>
Run Code Online (Sandbox Code Playgroud)

(注意minyear和maxyear属性来自表单默认值.)

有没有人找到一种方法来防止required在使用自定义验证规则时自动插入属性?

任何指导都将非常感谢.

谢谢!

克里斯

obs*_*ian 9

将required设置为false并将allowEmpty设置为true,应该为您执行此操作.

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

希望这可以帮助.

  • `'required'=> false`不是必需的,默认为null.只需`'allowEmpty'=> true`就足以确保'required'属性不会添加到input元素中. (4认同)