zf2 inputfilter - 如何 return 自定义验证失败

zf2 inputfilter - how to return a failed custom validation

我正在使用标准 ZF2 validators/filters 的输入滤波器。但是,我还扩展了 \My\InputFilter::isValid 方法以包括特定于域的验证,例如比较日期的特定部分。

在此方法中,我如何发出验证失败的信号,并为失败的元素提供特定的错误消息?我可以从方法中 return false 但这没有提供有关验证失败原因的更多信息。

即:

    public function isValid($context = null){

        $latestCollectionInput = $this->get('latestCollectionTime');
        $requestedCollectionTime = $this->get('requestedCollectionTime');

        $date1 = \DateTime::createFromFormat('d/m/Y H:i', $latestCollectionInput->getRawValue());
        $date2 = \DateTime::createFromFormat('d/m/Y H:i', $requestedCollectionTime->getRawValue());

        if($date1->format('N') !== $date2->format('N')){
            /* how to return failed validation for these elements */            
        }

        return parent::isValid($context);
    }

AbstractValidator class 中有一个 error 方法用于此目的。你可以找到它 here on line 329 on GitHub.

因此,当您在验证过程中发现某个值无效时,您可以这样做:

$this->error($key, $value);

通常密钥作为常量存储在验证器class中:

const ERROR_DATE_NOT_VALID = 'dateNotValid';
const ERROR_NOT_FUTURE_DATE = 'dateNotFutureDate';

并且相应的消息存储在$messageTemplates数组中:

protected $messageTemplates = array(
    self::ERROR_DATE_NOT_VALID => "Date must be a string and must be formatted as yyyy-mm-dd",
    self::ERROR_NOT_FUTURE_DATE => "The provided date must be in the future",
);

当输入过滤器收集验证失败的错误消息时,您传递的密钥将用于在模板列表中查找消息。这些消息将被返回。因此,当您使用这样的键抛出错误时:

$this->error(self::ERROR_DATE_NOT_VALID, $value);

将返回的消息将是:

"Date must be a string and must be formatted as yyyy-mm-dd"

阅读更多关于编写自定义验证器的信息here in the official ZF2 docs