How to get error message after entity validation

前端 未结 1 1280
暗喜
暗喜 2021-01-18 19:45

I\'m trying to get a clean error message after validating my Subscribe Entity :

/**
 * Subscribe
 * @UniqueEntity(\"email\")
 * @ORM\\Table(name=\"subscr         


        
相关标签:
1条回答
  • 2021-01-18 19:49

    try this:

               $validator = $this->get('validator');
               $errors = $validator->validate($email);
               if (count($errors) >0) {
                    $messages = [];
                    foreach ($errors as $violation) {
                         $messages[$violation->getPropertyPath()][] = $violation->getMessage();
                    }
                    return new JsonResponse($messages);
               }
    

    In this way I have create an array of errors, where the key is the not valid field, you can change this logic and add only the name of the field in front of the error and return a simple string.

    This code can works with all fields in the form

    0 讨论(0)
提交回复
热议问题