Symfony2 - How to validate an email address in a controller

Miloš picture Miloš · Aug 19, 2013 · Viewed 42.6k times · Source

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 validator in my controlelr in order to validate an email address?

This is possible by using the PHP preg_match for usere, but my question is if there is a possibility to use the Symfony already built in email validator.

Thank you in advance.

Answer

Ahmed Siouani picture Ahmed Siouani · Aug 19, 2013

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
    // ...
}
// ...