Zend输入过滤器“无论是”还是“场景都不可能?

问题描述 投票:1回答:1

我正在使用“zendframework / zend-inputfilter”v2.8.1。令我惊讶的是 - 我无法找到下一个场景的配置或设置选项:

我们有2个字段,需要填充其中一个或另一个字段。

例如:我们有两个字段:“年”和“年龄”。我想创建一个验证配置,其中需要设置“年”或“年龄”。

所以我的有效负载应该是这样的

{
    "year": 2000
}

要么

{
    "age": 18
}

要么

{
    "year": 2000,
    "age": 18
}

这应该是无效的:

{}

不幸的是,似乎其他问题(Conditionally required in Zend Framework's 2 InputFilter)要么过时,要么不准确。例如,如果我尝试使字段“年”可选,为有效负载

{
    "age": 18
}

{}

由于\Zend\InputFilter\BaseInputFilter::validateInputs中的代码,它被跳过了

        // If input is optional (not required), and value is not set, then ignore.
        if (! array_key_exists($name, $data)
            && ! $input->isRequired()
        ) {
            continue;
        }

如果我需要它,我在\Zend\InputFilter\Input::isValid遇到了条件

    if (! $hasValue && $required) {
        if ($this->errorMessage === null) {
            $this->errorMessage = $this->prepareRequiredValidationFailureMessage();
        }
        return false;
    }

我犹豫是否要覆盖BaseInputFilter或Input类,但从我现在看到的内容看来这似乎是我唯一的选择。不过也许我错过了一些东西。我会感激任何建议,谢谢!

php validation zend-framework2 zend-inputfilter zend-expressive
1个回答
2
投票

我相信你需要的是一个自定义验证器。

你可以做点什么。

class AgeYearValidator extends Zend\Validator\AbstractValidator
{
    const AGE = 'age';
    const YEAR  = 'year';
    const EMPTY  = 'empty';

    protected $messageTemplates = array(
        self::AGE => "Age is invalid. It must be between 1 to 110.",
        self::YEAR  => "Year is invalid. It must between 1900 to 2050.",
        self::EMPTY  => "Age and Year input fields are both empty."
    );

    public function isValid($value, $context = null)
    {
        $isValid = true;
        $year = null;
        $age = null;

        if(isset($context['year'])){
            $year = (int)$context['year'];
        }
        if(isset($context['age'])){
            $age = (int)$context['age'];
        }

        if(is_null($year) && is_null($age)) {
            $this->error(self::EMPTY);
            $isValid = false;
        } else {
            $isAgeValid = false;
            if($age > 0 && $age < 110) {
                $isAgeValid = true;
            }
            $isYearValid = false;
            if($year > 1900 && $year < 2050) {
                $isYearValid = true;
            }

            if($isAgeValid || $isYearValid) {
                $isValid = true;
            } else if (!$isAgeValid) {
                $this->error(self::AGE);
                $isValid = false;
            } else if (!isYearValid) {
                $this->error(self::YEAR);
                $isValid = false;
            }
        }

        return $isValid;
    }
}

我之前使用过类似的东西,效果很好。代码本身是不言自明的。你可以找到有关Zend Validators的更多信息。我可以看到他们在我的代码中添加了zend doco的一些缺失信息。

© www.soinside.com 2019 - 2024. All rights reserved.