How to validate emails outside of form with Symfony Validator Component
I'm building an invitation mechanism where owner of group can invite one or many users by providing email address(es) through rest api. This is very simple using Symfony Validator Component, but I noticed strange behavior when running tests. If I do not pass any emails I get wrong status code. 200 OK instead of 400 bad request.
After a while I found that using only \Symfony\Component\Validator\Constraints\Email() is not enough. Validator will pass null values and empty string, which is obvious wrong in my case. I had to also add NotBlank constraint, don't forget that in future.
At first I thought that this is a bug, but since it's covered by separate 2 tests here https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php#L35 I will leave it as it is.
Credit goes to the functional tests! :)
Snippet for further reference.
/**
* Validates single email (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;
}