简体   繁体   English

使用Doctrine2注释进行Symfony2验证

[英]Symfony2 Validation using Doctrine2 Annotations

I have the following Doctrine entity and I want to use its restriction also for validation. 我有以下Doctrine实体,我也想使用其限制进行验证。

/**
 * @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! 我使用以下验证,它适用于针对symfony的特定注释, 但不适用于Doctrine设置的限制!

// 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? 我该怎么做才能让symfony验证程序将学说限制用作设置?

Status quo: 现状:
I read [ 1 ] and [ 2 ] but so far I do not use forms because I have a controller returning JSON. 我读了[ 1 ]和[ 2 ],但到目前为止,我没有使用表单,因为我有一个返回JSON的控制器。 If you know how to make this work with forms would also help a lot! 如果您知道如何使用表格来完成这项工作,也将大有帮助!

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. 代码@ORM\\Column(type="string", length=40)仅将属性映射到数据库字段,并且如果您要使用原则创建架构,则将数据库字段的最大长度设置为等于40个字符。

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)
   */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM