为什么不考虑Symfony2验证约束?

时间:2013-05-06 13:49:45

标签: validation symfony yaml

我对Symfony 2.2中的验证限制有疑问。

似乎没有考虑“用户名”和“通过”的验证限制。但是“UniqueEntity”约束有效。

我不认为我在yaml语法中犯了错误。

这是yml语法:

Fastre\PhpFtpAdminBundle\Entity\Account:
properties:
    username:
        - Regex: {pattern: "/[a-zA-Z0-9]+/", message: Le nom d'utilisateur ne peut contenir que des lettres minuscules et majuscules et des chiffres.}
    pass: 
        - Length: {min: 8, minMessage: "Your name must have at least {{ limit }} characters."} 
constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: {fields: [username], groups: [registration]}

在控制器中:

if ($request->getMethod() === 'POST') {

        $form->bind($request);

        $data = $form->getData();



        $errors = $this->get('validator')->validate($data, array('Default'));

        //throw new \Exception($errors->count());

        if ($errors->count() == 0) { //the errors->count() is always set to 0!
            $em->flush();

            //TODO: i18n
            $this->get('session')
                    ->getFlashBag()
                    ->add('notice', 'Compte '.$account->getUsername().' modifié');

            return $this->redirect($this->generateUrl('account_list'));

        } else {


            foreach ($errors as $error) {
                $this->get('session')
                    ->getFlashBag()
                    ->add('warning', $error->getMessage()); 
            }

            return $this->render('FastrePhpFtpAdminBundle:Accounts:form.html.twig',
                array(
                    'form' => $form->createView(),
                    'action_path' => $this->generateUrl('account_view', array('id' => $id))
                    )
                );
        }

    }

1 个答案:

答案 0 :(得分:4)

这样做时:

$errors = $this->get('validator')->validate($data, array('Default'));

您只验证验证组Default。但由于您的设置,您的UniqueEntity约束仅适用于registration组:

{fields: [username], groups: [registration]}

因此,您可以删除UniqueEntity验证的组,也可以通过第二次调用验证它:

$errors = $this->get('validator')->validate($data, array('registration'));

http://symfony.com/doc/current/book/validation.html#validation-groups

在旁注中,而不是:

    $form->bind($request);
    $data = $form->getData();
    $errors = $this->get('validator')->validate($data, array('Default'));
    if ($errors->count() == 0) { 
        //do your stuff
    }

我强烈建议使用更简单的东西:

    $form->bind($request);

    if ($form->isValid()) {
        // do your stuff
    }

对于本案中的小组验证,请参阅:

http://symfony.com/doc/current/book/forms.html#book-forms-validation-groups