首页 > 解决方案 > ZF3 日期验证器选项

问题描述

我想在 ZF3 的表单类中检查日期,当我这样做时,它会使用给定的格式进行验证,如何验证给定的格式?

$inputFilter->add([
    'name'     => 'geboortedatum',
    'required' => true,
    'options' => [
        'format' => 'D-M-Y',
    ],            
    'filters'  => [                    
        ['name' => 'StringTrim'],
    ],                
    'validators' => [
        [
            'name'    => 'Date',
        ],
    ],
]);

标签: phpzend-framework3zend-validate

解决方案


您的配置中有两个错误。

第一个是您声明验证器选项(格式)的地方,它必须在声明验证器名称之后。

第二个是您使用的格式。除非您不想将日期表示为“ 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

推荐阅读