0

I have a form like this made with Symfony2:

class UsuarioRegistroType extends AbstractType {

  public function BuildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('email', 'email', array('label' => 'E-mail',  'required' => true))
....

Forms works fine, but if I write something like Email: asdf (not email address), I never get the error assosiated with this issue. Also, if I don't write anything, I don't get any error for required constraint.

Any idea with this issue? Thanks :)

1
  • The email type and the required flag depends on the browser. Run your form using chrome and it will work as expected. You will need to add server side validation for it to work as desired. See the section on form validation in the book: symfony.com/doc/current/book/forms.html Commented Mar 8, 2014 at 16:37

2 Answers 2

3

Required true don't validate anything. It just add a class required on the field on the form view. It's the html5 which validate that.

Try to add that on UsuarioRegistroType class :

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $collectionConstraint = new Collection(array(
        'email' => array(
            new NotBlank(array('message' => 'Email should not be blank.')),
            new Email(array('message' => 'Invalid email address.'))
        )
    ));

    $resolver->setDefaults(array(
        'constraints' => $collectionConstraint
    ));
}

don't forget the use statements :

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Symfony\Component\Validator\Constraints\Email;

use Symfony\Component\Validator\Constraints\NotBlank;

use Symfony\Component\Validator\Constraints\Collection;

Sign up to request clarification or add additional context in comments.

Comments

0

You have just used HTML5 validation, many barowser do not support this. With this old version of different famous browser also not support HTML5 validation.

I think you should use annotation for validation from serverside. I think you know about annotation , which you can use in your Entity class. In your enity class property you may defined your required validation rules using annotaion in symfony2.

Example:

use Symfony\Component\Validator\Constraints as Assert;

class Author
 {
     /**
      * @Assert\Email(
      *     message = "The email '{{ value }}' is not a valid email.",
      *     checkMX = true
      * )
      */
      protected $email;
 }

Helpful link from Symfony2 official documentation: Symfony2 Validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.