8

In my symfony application i need a custom validation constraint, which should check if an email is unique. This Constraint should be used as an annotation.

I followed the guideline from the symfony cookbooks, but i get exception:

Attempted to load class "unique.email.validator" from the global namespace. Did you forget a "use" statement?

This is the code i have in my Unique Email Constraint class:

<?php

namespace MyApp\AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Class UniqueEmail
* @package MyApp\AppBundle\Validator\Constraints
* @Annotation
*/
class UniqueEmail extends Constraint
{
  public $message = 'The Email already exists.';

  public function validatedBy()
  {
      return 'unique.email.validator';
  }
}

And this is the code from my unique EmailValidator:

namespace MyApp\AppBundle\Validator\Constraints;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueEmailValidator extends ConstraintValidator
{
   /**
    * @var EntityManager
    */
   protected $em;

   public function __construct(EntityManager $entityManager)
   {
      $this->em = $entityManager;
   }

  public function validate($value, Constraint $constraint)
  {
      $repository = $this->em->getRepository('AppBundle:Advertiser');
      $advertiser = $repository->findOneBy(array(
          'email' => $value
      ));

      if ($advertiser) {
          $this->context->buildViolation($constraint->message)
              ->addViolation();
      }
  }
} 

And last but not least my services.yml:

   services:
       unique.email.validator:
           class: MyApp\AppBundle\Validator\Constraints\UniqueEmailValidator
           arguments:
               entityManager: "@doctrine.orm.entity_manager"
           tags:
               - { name: validator.constraint_validator, alias:      unqiue.email.validator }

Does anyone have any idead how to solve it?

2
  • Use "app/console container:debug unique.email.validator" to verify your services file is being loaded. Commented Apr 11, 2015 at 14:14
  • 1
    Do you really have to add the validatedBy() function in your UniqueEmail Class? My understanding was it is unnecessary symfony.com/doc/master/validation/… Commented Jun 3, 2018 at 15:56

1 Answer 1

7

In your services.yml the alias is misspelled: 'unqiue.email.validator' instead of 'unique.email.validator'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.