0

I have the following Doctrine entity and I want to use its restriction also for validation.

/**
 * @var string
 *
 * @ORM\Column(type="string", length=40)
 * @Assert\Valid
 */
private $birthName;

I use the following validation, which works for symfony specific annotaions but not Doctrine set restrictions!

// Validate data
$validator = $this->get('validator');
$errors = $validator->validate($user);

if (count($errors) > 0) {
    $response = new JsonResponse(array(
        'error' => 'User could not be created.' . PHP_EOL . (string)$errors
    ));
    $response->setStatusCode(400);

    return $response;
}

What can I do to let symfony validator use the doctrine restrictions as settings?

Status quo:
I read [1] and [2] but so far I do not use forms because I have a controller returning JSON. If you know how to make this work with forms would also help a lot!

Community
  • 1
  • 1
lony
  • 6,733
  • 11
  • 60
  • 92

1 Answers1

3

Doctrine mappings have nothing to do with validation. The code @ORM\Column(type="string", length=40) only maps a property to a database field, and sets max length of a database field to be equal 40 characters, if you would create a schema using doctrine.

But thus doesn't take any part of the validation process. So you need to set an assertion rule by something like

   /**
   * @Assert\Length(max = 40)
   */
Dmitry Malyshenko
  • 3,001
  • 1
  • 12
  • 20