有没有办法在Symfony中验证ISO8601日期?

时间:2014-07-10 23:52:06

标签: validation symfony iso8601

我如何验证日期是ISO8601,特别是RFC3339?我需要编写一些自定义正则表达式吗?

3 个答案:

答案 0 :(得分:4)

我认为,正则表达式是解决方案,因为Validator约束不支持此。

Here is the regular expression for that

它是您要验证的表单输入吗?

答案 1 :(得分:2)

事实上,除了提议的正则表达式之外,我知道的唯一方法是添加自己的回调验证器:

        ->add('occured_at', 'text', [
            'constraints' => [
                new Assert\NotBlank,
                new ASsert\Callback(function($date, $context) {
                    if (false === \DateTime::createFromFormat(\DateTime::ISO8601, $date)) {
                        $context->addViolation("$date is not at ISO8601 format.");
                    }
                })
            ],
        ])

答案 2 :(得分:1)

仅限SYMFONY 3.1

您可以使用

@Assert\DateTime(format="Y-m-d\TH:i:sO")

请参阅:http://symfony.com/doc/current/reference/constraints/DateTime.html

ISO8601格式“Y-m-d \ TH:i:sO”;

http://php.net/manual/en/class.datetime.php

编辑1:

您可以直接使用格式“c”,ISO 8601格式的快捷方式

(ISO 8601日期(在PHP 5中添加):http://php.net/manual/en/function.date.php