php - ZF3 日期验证器选项
问题描述
我想在 ZF3 的表单类中检查日期,当我这样做时,它会使用给定的格式进行验证,如何验证给定的格式?
$inputFilter->add([
'name' => 'geboortedatum',
'required' => true,
'options' => [
'format' => 'D-M-Y',
],
'filters' => [
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => 'Date',
],
],
]);
解决方案
您的配置中有两个错误。
第一个是您声明验证器选项(格式)的地方,它必须在声明验证器名称之后。
第二个是您使用的格式。除非您不想将日期表示为“ Wed-Jan-2020 ”(今天的日期),否则正确的格式是d-m-Y
.
根据PHP 文档,格式参数为:
| 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 声明是:
$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
推荐阅读
- html - 如何在 Hugo 中使用 if else 语句和 CSS
- openmodelica - 让 OpenModelica 运行时遇到问题/错误代码 1
- c# - .net 中的 MongoDB 过滤器查询从 SQL 转换
- kotlin - 掌握 Kotlin 代表的窍门
- sql - Postgresql 排除基于子查询的结果
- javascript - 在 React 中访问第二层数组
- python-3.x - 将数据透视表转换为 Python 数据框
- google-sheets - Google 表格和 ImportXML - 缩小结果范围
- python - Pandas,遍历数据框项并基于列值构建新的数据框
- bash - Bash:如何存储在变量中显示带有 \n 的变量的命令