MiloŇ° MiloŇ° - 1 year ago 195
PHP Question

Symfony2 - How to validate an email address in a controller

There is an email validator in symfony that can be used in a form:

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 Source

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(

    // $errors is then empty if your email address is valid
    // it contains validation error message in case your email address is not valid
    // ...
// ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download