Symfony2 - How to validate an email address in a controller

后端 未结 6 1485
走了就别回头了
走了就别回头了 2021-02-01 18:38

There is an email validator in symfony that can be used in a form: http://symfony.com/doc/current/reference/constraints/Email.html

My question is: How can I use this val

6条回答
  •  不知归路
    2021-02-01 19:20

    Why does no one mention that you can validate it with in FormBuilder instance using 'constraints' key ??? First of all, read documentation Using a Form without a Class

    'constraints' =>[
        new Assert\Email([
            'message'=>'This is not the corect email format'
        ]),
        new Assert\NotBlank([
            'message' => 'This field can not be blank'
        ])
    ],
    

    Works fine with symfony 3.1

    Example:

    namespace SomeBundle\Controller;
    
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\Form\Extension\Core\Type;
    use Symfony\Component\Validator\Constraints as Assert;
    
    class DefaultController extends Controller
    {
    
        /**
         * @Route("kontakt", name="_kontakt")
         */
        public function userKontaktAction(Request $request) // access for all
        {
    
            $default = array('message' => 'Default input value');
            $form = $this->createFormBuilder($default)
            ->add('name', Type\TextType::class,[
                'label' => 'Nazwa firmy',
            ])
            ->add('email', Type\EmailType::class,[
                'label' => 'Email',
                'constraints' =>[
                    new Assert\Email([
                        'message'=>'This is not the corect email format'
                    ]),
                    new Assert\NotBlank([
                        'message' => 'This field can not be blank'
                    ])
                ],
            ])
            ->add('phone', Type\TextType::class,[
                'label' => 'Telefon',
            ])
            ->add('message', Type\TextareaType::class,[
                'label' => 'Wiadomość',
                'attr' => [
                    'placeholder' => 'Napisz do nas ... '
                ],
            ])
            ->add('send', Type\SubmitType::class,[
                'label' => 'Wyślij',
            ])
            ->getForm();
    
            $form->handleRequest($request);
    
            if ($form->isValid()) {
                // data is an array with "name", "email", and "message" keys
                $data = $form->getData();
                // send email
                // redirect to prevent resubmision
                var_dump($data);
            }
            
            return $this->render('SomeBundle:Default:userKontakt.html.twig', [
                'form' => $form->createView()
            ]);
        }
    
    }
    

    Result:

    See the documentaion about available validation types. http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html

    If you want to check what are the available keys other than message, go to documentation at:

    http://symfony.com/doc/current/reference/constraints/Email.html

    or navigate to:

    YourProject\vendor\symfony\symfony\src\Symfony\Component\Validator\Constraints\Email.php

    from there, you will be able to see what else is available.

    public $message = 'This value is not a valid email address.';
    
    public $checkMX = false;
    
    public $checkHost = false;
    
    public $strict; "
    

    Also note that I created and validated form inside the controller which is not a best practice and should only be used for forms, which you will never reuse anywhere else in your application.

    Best practice is to create forms in a separated directory under YourBundle/Form. Move all the code to your new ContactType.php class. (don't forget to import FormBuilder class there as it will not extend your controller and will not have access to this class through '$this')

    [inside ContactType class:]

    namespace AdminBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Form\Extension\Core\Type;
    use Symfony\Component\Validator\Constraints as Assert;
    

    [inside your controller:]

    use YourBundle/Form/ContactType;
    // use ...
    
    //...
    $presetData = []; //... preset form data here if you want to
    $this->createForm('AdminBundle\Form\FormContactType', $presetData) // instead of 'createFormBuilder'
    ->getForm();
    // render view and pass it to twig templet...
    // or send the email/save data to database and redirect the form
    

提交回复
热议问题