douhan8581 2014-06-21 11:41
浏览 48
已采纳

在我的验证器中实现可选输入

I've made a Validator that accepts rule objects to define validation rules.

$rules['name1'] = [new NotEmpty(), new MaxChars(20), new Alpha(true)];
$rules['name2'] = [new MaxChars(20), new Alpha(true)];

What my validator does with these rule objects, is that whenever it tries to validate an input, it will loop through every rule object and call the check() method to see whether it's valid or not. And then return true or false with a list of the errors.

$validator = new Validator();

$validator->setRule('name1', $rules['name1']); //void
$validator->setRule('name2', $rules['name2']); //void

$validator->validate('name1', 'John Doe'); //true
$validator->validate('name2', ''); //should return true, but returns false

What would be a good way to indicate that an input can be optional?

I have a rule class NotEmpty, but if I just leave it out of my rule declaration, my validator is still going to loop and check through every rule object that's been declared. While it should be ignoring the rules and just return true. And that would be the ideal scenario.

I've thought about tightly coupling the NotEmpty class with my Validator class, e.g. checking if it's present in the rule array or not (which means required or optional). But I would rather have my classes decoupled, and I don't know if it's possible like that.

If anyone has a good suggestion, I can execute the further implementation myself.

  • 写回答

2条回答 默认 最新

  • douluoqiu4538 2014-06-21 11:51
    关注

    I would add a $required param to the setRule() method:

    $validator->setRule('name1', $rules['name1'], $required = TRUE);
    

    This is because all rules would been affected by this extra restriction, meaning any of the rules would need that parameter otherwise.

    Having the parameter in setRule, your validator code might look like:

    (Pseudo code, hope it is understandable):

    if(!value_present($value)) {
        if(!$rule->required) {
            // no validation needed
            return true;
        } else {
           throw Exception('...');
        }
    }
    
    // Check constraints now. Constraint's code does not need to know 
    // about the $required anymore
    foreach($rule->constraints as $c) {
        $c->apply($value);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?