Symfony验证器不验证发布数据

时间:2016-11-04 18:44:03

标签: symfony

我正在转向Symfony,并且验证我发送的帖子数据存在问题。我遵循了官方文档,并在实体中输入了这个属性:

/**
 * @ORM\Column(type="string", length=100)   
 * @Assert\Length(
 *      min = 3,
 *      max = 50,
 *      minMessage = "Your name must be at least {{ limit }} characters long",
 *      maxMessage = "Your name cannot be longer than {{ limit }} characters"
 * )
 */
private $name;

控制器中的代码是:

    $student = new Student();
    $student->setName($request->query->get('name'));
    $student->setBirth_Date( new \DateTime($request->query->get('date') ) );

    $validator = $this->get('validator');
    $errors = $validator->validate($student);

    if (count($errors) > 0) {
        /*
         * Uses a __toString method on the $errors variable which is a
         * ConstraintViolationList object. This gives us a nice string
         * for debugging.
         */
        $errorsString = (string) $errors;

        return new Response('Validation errors: '. $errorsString);
    }

    $em = $this->getDoctrine()->getManager();
    $em->persist($student);

    // actually executes the queries (i.e. the INSERT query)
    $em->flush();

    return new Response('Saved new student with id '. $student->getId());

为什么它没有验证,我总是在数据库中获得新条目?我错过了什么吗?

2 个答案:

答案 0 :(得分:0)

请检查您配置验证注释constrait,请阅读:https://symfony.com/doc/current/validation.html#configuration 并清除缓存

app/console cache:clear 

或symfony3

bin/console cache:clear

答案 1 :(得分:0)

必须将itertools.izip_longest放入配置中。没有在文档中找到这个。 还需要在长度之前断言NotBlank()以进行第二次验证。

validation: { enabled: true, enable_annotations: false  }