How to add validation for unique field in doctrine?

The essence
<?php
OwrBundle namespace\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="OwrBundle\Entity\Repository\UserRepository")
 * @ORM\Table(name="`user`")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity(
 * fields={"username", "phone"},
 * message="duplicate"
 * )
*/
class User implements UserInterface
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer", name="user_id")
 * @ORM\GeneratedValue(strategy="AUTO")
*/
 protected $id;

/**
 * @ORM\Column(type="string", name="email", unique=true)
 * @Assert\Email(
 * message = "email",
 * checkMX = true
 * )
*/
 protected $username;

/**
 * @ORM\Column(type="string", length=13, unique=true)
 * @Assert\Regex(
 * pattern = "/^\+\d{12}$/",
 * message = "correct"
 * )
*/
 protected $phone;

/**
...
**/
}</property-->
br><br> Enter a phone number that is already in the database.<br> But the validator doesn't give error.<br> It gives itself the database:<br><pre><code>SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "uniq_8d93d649444f97dd" DETAIL: Key (phone)=(+180863723139) already exists.</code></pre><br><br> How to force validator to catch errors?
June 14th 19 at 18:52
1 answer
June 14th 19 at 18:54
Solution
You have the UniqueEntity validator for two fields specified. It checks the uniqueness of the combination "username" and "phone". You need to split them into two separate validator, and you don't specify both fields in one.

Find more questions by tags Doctrine ORMSymfony