您的配置中有两个错误。
第一个是您声明验证器选项(格式)的地方,它必须在声明验证器名称之后。
第二个是您使用的格式。除非您不想将日期表示为“Wed-Jan-2020”(今天的日期),否则正确的格式是 d-m-Y。
根据PHP documentation,格式参数为:
| character | description | example |
|-----------|----------------------------------------------------------|------------------------|
| D | A textual representation of a day, three letters | Mon through Sun |
| M | A short textual representation of a month, three letters | Jan through Dec |
| d | Day of the month, 2 digits with leading zeros | 01 to 31 |
| m | Numeric representation of a month, with leading zeros | 01 through 12 |
| Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
正确的输入过滤器声明是:
$inputfilter = new \Zend\InputFilter\InputFilter();
$inputfilter->add([
'name' => 'geboortedatum',
'required' => true,
'filters' => [
['name' => \Zend\Filter\StringTrim::class]
],
'validators' => [
[
'name' => \Zend\Validator\Date::class,
'options' => [
'format' => 'd-m-Y'
]
]
]
]);
$dates = [
'1977-05-23',
'23-05-1977',
'30-02-2020'
];
foreach ($dates as $date) {
$data['geboortedatum'] = $date;
$inputfilter->setData($data);
echo 'Date "' . $data['geboortedatum'] . '" is ';
if ($inputfilter->isValid()) {
echo 'valid';
} else {
echo 'invalid. Errors:'
. PHP_EOL . "\t"
. implode($inputfilter->getMessages()['geboortedatum'], PHP_EOL . "\t");
}
echo PHP_EOL;
}
结果:
Date "1977-05-23" is invalid. Errors:
The input does not fit the date format 'd-m-Y'
The input does not appear to be a valid date
Date "23-05-1977" is valid
Date "30-02-2020" is invalid. Errors:
The input does not fit the date format 'd-m-Y'
The input does not appear to be a valid date