Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - How to validate an email address in a controller

Tags:

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.

like image 800
Milos Cuculovic Avatar asked Aug 19 '13 14:08

Milos Cuculovic


People also ask

How do you validate email addresses in input?

The best way to "validate" an email addresses is to simply have them type it twice and run a Regex check that gives a WARNING to the user that it doesn't look like a valid email address if it does not match the pattern, and asks the user to double check.


1 Answers

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     // ... } // ... 
like image 157
Ahmed Siouani Avatar answered Oct 09 '22 07:10

Ahmed Siouani