Symfony2 - How to validate an email address in a controller Symfony2 - How to validate an email address in a controller symfony symfony

Symfony2 - How to validate an email address in a controller


By using validateValue method of the Validator service

use Symfony\Component\Validator\Constraints\Email as EmailConstraint;// ...public function customAction(){    $email = 'value_to_validate';    // ...    $emailConstraint = new EmailConstraint();    $emailConstraint->message = 'Your customized error message';    $errors = $this->get('validator')->validateValue(        $email,        $emailConstraint     );    // $errors is then empty if your email address is valid    // it contains validation error message in case your email address is not valid    // ...}// ...


I wrote a post about validating email address(es) (one or many) outside of forms

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

It also covers a common bug where you validate against Email Constraint and forget about NotBlank

/** * Validates a single email address (or an array of email addresses) * * @param array|string $emails * * @return array */public function validateEmails($emails){    $errors = array();    $emails = is_array($emails) ? $emails : array($emails);    $validator = $this->container->get('validator');    $constraints = array(        new \Symfony\Component\Validator\Constraints\Email(),        new \Symfony\Component\Validator\Constraints\NotBlank()    );    foreach ($emails as $email) {        $error = $validator->validateValue($email, $constraints);        if (count($error) > 0) {            $errors[] = $error;        }    }    return $errors;}

I hope this helps


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 classuse 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...