Symfony 3 约束验证日期或日期时间

Fab*_*ice 5 validation date constraints symfony fosrestbundle

我尝试通过 Symfony (3.2) 中的表单验证来验证日期(或日期时间)。

我正在使用 FOSRestBundle 来使用请求中的 json (因为我尝试开发我的个人 API)

但我尝试了很多格式:

  • 2017-04-09
  • 2009年4月17日
  • 对于日期时间:
    • 2017-04-09 21:12:12
    • 2017-04-09T21:12:12
    • 2017-04-09T21:12:12+01:00
  • ...

但表单无效,我总是收到此错误:此值无效

我的控制器的功能

public function postPlacesAction(Request $request) {
    $place = new Place();
    $form = $this->createForm(PlaceType::class, $place);

    $form->handleRequest($request);

    if ($form->isValid()) {
        return $this->handleView($this->view(null, Response::HTTP_CREATED));
    } else {
        return $this->handleView($this->view($form->getErrors(), Response::HTTP_BAD_REQUEST));
    }
}
Run Code Online (Sandbox Code Playgroud)

我的实体

class Place
{
    /**
     * @var string
     *
     * @Assert\NotBlank(message = "The name should not be blank.")
     */
    protected $name;

    /**
     * @var string
     *
     * @Assert\NotBlank(message = "The address should not be blank.")
     */
    protected $address;

    /**
     * @var date
     *
     * @Assert\Date()
     */
    protected $created;

    // ....
    // Getter and setter of all var
Run Code Online (Sandbox Code Playgroud)

我的实体类型

class PlaceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
        $builder->add('address');
        $builder->add('created');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'MyBundle\Entity\Place',
            'csrf_protection' => false
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

请求示例(我正在使用 Postman)

我不确定我使用的格式是否正确,或者我的文件中是否缺少任何内容:/

请你打开我心中的灯好吗?!:)

非常感谢你的帮助。法布里斯

Pig*_*all 3

您的表单类型中的字段存在问题created。当您created使用语法添加字段时,将应用$builder->add('created');默认类型,并且输入数据是字符串,而不是实例。Symfony\Component\Form\Extension\Core\Type\TextType1997-12-12DateTime

要解决此问题,您应该传入DateType第二个参数:$builder->add('created', 'Symfony\Component\Form\Extension\Core\Type\DateType');。这种表单类型有一个转换器,它将输入数据转换1997-12-12DateTime实例。

有关 Symfony 表单类型的更多信息,请查看表单类型参考