0

I've came across this problem a few times, but could never find a solution, only work arounds.

Lets say I have multiple 10 jobs, but depending on the answers given the validation rules are different.

foreach($jobs as $job){

    if(!$this->Job->validates()){
        echo 'Oh no, it didn't validate';
    }

}

The main problem I'm finding is if I set a rule that was triggered only by the first job.

if($this->data['Job']['type'] == 'special'){
    $this->validator()->add('special_field', 'notEmpty', array(
        'rule' => array('notEmpty'),
        'message' => 'Please provide data'
    ));
}

It would also apply to the other 9. So the rules are persistent between calls. So can could remove the rule if it exists.

if($this->data['Job']['type'] == 'special'){
    $this->validator()->add('special_field', 'notEmpty', array(
        'rule' => array('notEmpty'),
        'message' => 'Please provide data'
    ));
}else{
    $this->validator()->remove('special_field', 'notEmpty');
}

But if the rule doesn't exist when it tries to remove it a Fatal Error is thrown.

Is there any way to check a rule exists before I remove it or a way to clear dynamic rules at the start of beforeValidate?

4

2 回答 2

1

您可以使用该ModelValidator::getField方法获取字段的所有规则,并使用它来检查特定规则是否存在。

于 2013-07-31T13:05:42.487 回答
0

有趣的问题。

我没有对此进行测试,但似乎可以使用:

$this->validator()->remove('special_field');

删除字段的所有规则。

于 2013-07-31T13:05:03.567 回答