dou4624 2015-10-01 14:32
浏览 47
已采纳

使用Doctrine2注释进行Symfony2验证

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!

  • 写回答

1条回答 默认 最新

  • doufang3001 2015-10-01 15:11
    关注

    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)
       */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效