如何在Symfony中使用带有null的Assert/Type?

Ale*_*der 5 validation assert symfony

是否可以使用确切类型OR null验证实体的属性?换句话说,该属性可以具有精确类型的optinal值.

例如,可以设置属性$ date(\Datetime类型):

/**
 * @ORM\Column(type="datetime", nullable=true)
 * @Assert\Type("\DateTime")
 */
protected $date;
Run Code Online (Sandbox Code Playgroud)

不要介意nullable=true@ORM\Column一节,它仅适用于DB-水平,而不是模型验证.

问题是:如果$ date不存在,则错误为:

Expected argument of type "DateTime", "NULL" given

Jak*_*zak 4

尝试使用@Assert\DateTime()

/**
 * @ORM\Column(type="datetime", nullable=true)
 * @Assert\DateTime()
 */
protected $date;
Run Code Online (Sandbox Code Playgroud)

Type强制字段为指定类型的实例,而其他约束则验证值是否不为空(NotNull等除外)。

请记住,@Assert\DateTime()它还接受正确的日期时间字符串。但是您可以使用适当的设置器来处理它,以强制该值为 null 或\DateTime