Symfony2 - How to validate an email address in a controller

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


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