【问题标题】:Form validation: only one validator of the chain should check against empty/null values, the rest of the validators should not表单验证:链中只有一个验证器应该检查空/空值,其余的验证器不应该
【发布时间】:2013-11-19 11:59:37
【问题描述】:

我有这个id_role 输入,它根据另一个输入internet_access 的值进行验证。 id_role 的验证器链有一个回调验证器,它必须检查空/空值,该链中的其他验证器必须只检查填充值。

我已经通过$id_role->setContinueIfEmpty(true) 对空/null 值进行了检查,但这适用于链中的每个验证器。我需要它只应用于链的回调验证器。

这是实际的id_role 输入:

$id_role = new Input('id_role');
$id_role->setContinueIfEmpty(true); //this allows to check against empty/null values
$id_role->getFilterChain()
        ->attach($FilterInt);

$id_role->getValidatorChain()
        ->attach(new Validator\Callback(function($value, $context=array()){
            return isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0 ? false : true;
        }))
        ->attach(new Validator\Db\RecordExists(...);

所以我的问题是回调验证器工作正常,但它在DbRecordExists 上失败,因为它试图找到一个空的记录。 DbRecordExists 必须仅在 id_role 实际被填充时才尝试查找记录。

有没有办法以优雅的方式(在输入过滤器和/或输入中)做我想做的事?

【问题讨论】:

    标签: php validation zend-framework2


    【解决方案1】:

    ValidatorChain::attach方法的第二个参数是$breakChainOnFailure,默认值为false。

    http://framework.zend.com/manual/2.2/en/modules/zend.validator.validator-chains.html查看文档

    你应该修改你的代码:

    $id_role->getValidatorChain()
        ->attach(
            new Validator\Callback(
                function($value, $context=array()){
                    return isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0 ? false : true;
                }
            ),
            true //$breakChainOnFailure
        )
        ->attach(new Validator\Db\RecordExists(....));
    

    【讨论】:

    • 谢谢,如果失败,这将有助于它打破链,但我最需要的是让第二个验证器 DbRecordExists 跳过空/空值。
    • 我的问题仍未得到解答。
    【解决方案2】:

    我认为没有办法只在链的特定验证器中检查空/空值,因为当我执行$id_role->setContinueIfEmpty(true) 时,它会影响整个验证器链,而不仅仅是一个特定的验证器,这是正确的行为.

    因此,为了完成我需要的操作,我必须将 DbRecordExists Validator 放入 Callback Validator 并仅在值不为空/null 时手动对其进行验证:

    $id_role = new Input('id_role');
    $id_role->setContinueIfEmpty(true);
    $id_role->getFilterChain()
            ->attach($FilterInt);
    
    $id_role->getValidatorChain()
            ->attach(new Validator\Callback(function($value, $context=array()){
                if (isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0) {
                    return false;
                }
    
                if ($value !== 0) {
                    $dbRecordExists = new Validator\Db\RecordExists(...);
    
                    if (!$dbRecordExists->isValid($value)) {
                        return false;   
                    }
                }
    
                return true;
            }));
    

    我不知道这是否是最好的解决方案,但它确实有效。我希望这可以对遇到同样问题的其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多