Symfony2:递归验证 [英] Symfony2 : Recursive Validation

查看:38
本文介绍了Symfony2:递归验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些验证器的实体(不是表单).

所以我使用 $validator->validate($entity),但它不验证我的子对象(实体类有一些其他实体类和一些验证器).>

是否有一种自动"的方式来做到这一点,或者我必须为每个人做 $errorList->addAll($validator->validate($entity)); ?

解决方案

要允许对对象进行递归验证,您可以简单地使用约束 @Assert\Valid

示例
假设一个人有一个必填的姓氏

class Person{/*** @Assert\NotNull* @var 字符串*/受保护的 $lastName;}

你有一个产品,它有一个买家(Person)

class 产品{/*** @Assert\NotNull* @Assert\有效* @var 人*/受保护的 $buyer;}

通过使用 NotNullValid,每次验证 Product 模型时,它都会检查:

  • 它有买家
  • 买家有一个lastName

I've got an entity with some validators (not a form).

So I use $validator->validate($entity), but it doesn't validate my sub-ojects (the entity class has some others entity classes with some validators).

Is there an "automatic" way to do this, or I have to do $errorList->addAll($validator->validate($entity)); for each of them ?

解决方案

To allow recursive validation over objects you can simply use the Constraint @Assert\Valid

Example
Say a person has a mandatory last name

class Person
{
    /**
     * @Assert\NotNull
     * @var string
     */
    protected $lastName;
}

And you have a product, which have a buyer (Person)

class Product
{
    /**
     * @Assert\NotNull
     * @Assert\Valid
     * @var Person
     */
    protected $buyer;
}

By having NotNull and Valid, each time you validate the Product model it will check that:

  • It has a buyer
  • The buyer has a lastName

这篇关于Symfony2:递归验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆