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条)

报告相同问题?

悬赏问题

  • ¥15 python变量和列表之间的相互影响
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)