基于两个字段的Symfony2表单验证 [英] Symfony2 form validation based on two fields

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

问题描述

我目前正在开发一个用户可以购买礼品卡的网站。我正在使用使用CraueFormFlow包的三步表单,并且所有步骤都与步骤有关。我可以验证每个简单的Assert(如不是空白,电子邮件,重复字段等),但我面临的情况是,用户可以选择0张礼品卡并进入下一页。



用户可以使用两种不同的方式选择他们想要购买的礼品卡的数量:一张用于25美元的礼品卡,另一张用于50美元的礼品卡。所以我不能只让一个验证者说不允许值0。验证器必须防止用户在数量上(25 $和50 $)保留数量0。

有谁知道如何进行自定义验证以查找在两个字段的值?



在此先感谢!

解决方案

你有许多解决方案。



最简单的方法是添加回调约束给你的模型类。



另一种方法是创建自定义约束和它的自定义约束相关的验证器。您有一本食谱说明如何创建自定义验证限制
这是最好的方法。



由于约束不适用于属性,而是适用于类,所以必须指定它重写 - > getTargets()约束类的方法:

  class MyConstraint扩展约束
{
// ...

public function getTargets()
{
return Constraint :: CLASS_CONSTRAINT;






$ p所以传递的值为 $ value - > isValid()方法的参数将包含整个类的值,而不仅仅是单个属性的值。

I am currently developing a Website in which user may buy gift cards. I am using a three step form using the CraueFormFlow bundle and everything is concerning the steps. I am able to validate every simple Assert (like not blank, email, repeated fields, etc) but I am facing the situation where, user may select 0 gift cards and proceed to the next page.

The users may choose the quantity of giftcards they want to buy using two separate : one for 25$ gift cards and one for 50$ gift cards. So I can't just put a validator saying "value 0 is not allowed". The validator must prevent a user from leaving the quantity "0" in both amount (25$ and 50$).

Does anyone know how to make a custom validation looking for the values in two fields?

Thanks in advance!

解决方案

You have many solutions for this.

The easiest one is to add a Callback constraint to your model class.

Another way to do it would be to create your custom constraint and its associated validator. You have a cookbook explaining how to create a custom validation constrain. This is the best approach to do it.

As your constraint does not apply to a property but to a class, you must specify it overriding the the ->getTargets() method of your constraint class:

class MyConstraint extends Constraint
{
    // ...

    public function getTargets()
    {
        return Constraint::CLASS_CONSTRAINT;
    }
}

So the value passed as $value argument of the ->isValid() method will contain values of the whole class and not only of a single property.

这篇关于基于两个字段的Symfony2表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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