【问题标题】:Is there a way to validate a ISO8601 date in Symfony?有没有办法在 Symfony 中验证 ISO8601 日期?
【发布时间】:2014-07-10 23:52:05
【问题描述】:

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

【问题讨论】:

标签: validation symfony iso8601


【解决方案1】:

我认为,正则表达式是解决方案,因为验证器约束不支持这一点。

Here is the regular expression for that

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

【讨论】:

    【解决方案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.");
                        }
                    })
                ],
            ])
    

    【讨论】:

    【解决方案3】:

    仅适用于 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

    【讨论】:

    • 这对我不起作用,它说格式选项是不允许的。
    • 你是哪个版本的 symfony?
    • 在github上得到了答案,它需要3.1或更高版本。但是这个选项太明显了,我什至无法想象没有它这个验证器怎么存在。
    • 也适用于 Symfony 5.3。
    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 2021-04-21
    • 2017-10-26
    • 1970-01-01
    相关资源
    最近更新 更多