Symfony2 - How to validate an email address in a controller

后端 未结 6 1475
走了就别回头了
走了就别回头了 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

    If you're creating the form in the controller itself and want to validate email in the action, then the code will look like this.

    // add this above your class
    use Symfony\Component\Validator\Constraints\Email;
    
    public function saveAction(Request $request) 
    {
        $form = $this->createFormBuilder()
            ->add('email', 'email')
            ->add('siteUrl', 'url')
            ->getForm();
    
        if ('POST' == $request->getMethod()) {
            $form->bindRequest($request);
    
            // the data is an *array* containing email and siteUrl
            $data = $form->getData();
    
            // do something with the data
            $email = $data['email'];
    
            $emailConstraint = new Email();
            $emailConstraint->message = 'Invalid email address';
    
            $errorList = $this->get('validator')->validateValue($email, $emailConstraint);
            if (count($errorList) == 0) {
                $data = array('success' => true);
            } else {
                $data = array('success' => false, 'error' => $errorList[0]->getMessage());
            }
       }
    
       return $this->render('AcmeDemoBundle:Default:update.html.twig', array(
           'form' => $form->createView()
       ));
    }
    

    I'm also new and learning it, any suggestions will be appreciated...

提交回复
热议问题