Symfony2:提交表单和多个验证组时忽略验证约束

时间:2014-03-03 19:35:40

标签: validation symfony assert

问题:

提交表单时会忽略Length约束。

实体:

/**
 * @Assert\Length(min = "6")
 * @Assert\NotBlank(groups={"registro"})
 */
private $password;

FormType:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
    'data_class' => 'BikeApp\UsuariosBundle\Entity\Usuarios',
    'validation_groups' => array('default', 'registro')
    ));     
}

2 个答案:

答案 0 :(得分:2)

根据常量Symfony\Component\Validator\Constraint::DEFAULT_GROUP,默认验证组不是default,而是Default

答案 1 :(得分:0)

由于某些原因,它未从您的实体调用,因此请尝试在buildForm()方法中添加验证约束

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('nombre')
        ->add('apellidos')  
        ->add('email', 'email', array('label' => 'Correo electrónico', 'attr' => array(
            'placeholder' => 'usuario@servidor'
        )))
        ->add('password', 'repeated', array(
            'type' => 'password',
            'invalid_message' => 'Las dos contraseñas deben coincidir',
            'first_options'   => array('label' => 'Contraseña'),
            'second_options'  => array('label' => 'Repite Contraseña'),
            'required'        => true,
            'constraints'     =>array(new Assert\Length(array('min' => 6,'message'=>'La contraseña debe tener al menos {{ limit }} carácteres')))
            ))
        ->add('fechaNacimiento', 'birthday', array('required'=> false, 'widget' => 'single_text'))
        ->add('dni')
        ->add('newsletter', 'checkbox', array('required' => false));    
}

不要忘记在表单类之前添加用途

use Symfony\Component\Validator\Constraints as Assert;