验证器调用之间的动态规则验证持久性

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?

Interesting problem.

I have not tested this, but it seems that one can use:

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

to remove all the rules for a field.

You can use the ModelValidator::getField method to get all rules of a field and use that to check if a specific rule exists. See.