断言表达式验证在Symfony 2.4中的属性级别上不起作用 [英] Assert Expression validation not working at attribute level in Symfony 2.4

查看:68
本文介绍了断言表达式验证在Symfony 2.4中的属性级别上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过@Assert \ Expression(

I am trying to validate an attribute at a field level by the @Assert\Expression (http://symfony.com/doc/2.4/reference/constraints/Expression.html).

它可以在以下代码的类级别使用:

It works at a class level with this code:

/**
 * Foo
 * 
 * @ORM\Table(name="foo")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity("slug")
 * @Assert\Expression(
 *     "this.getPriceFor2PaxStandard() != null or (this.getPriceFor2PaxStandard() == null and !this.isPriceForAccLevelRequired('standard'))",
 *     message="The price for 2 pax standard is required",
 *     groups={"agency_tripEdit_finalsave"}
 * )
 * 
 */
class Foo implements ISpellcheckerLocaleProvider, ProcessStatusAware, DataTransformer
{

但是如果我在属性级别使用相同的代码(应该没问题)不起作用:

but if I use the same code (which should be fine) at attribute level is not working:

/**
     * @var decimal
     *
     * @ORM\Column(name="price_for_2_pax_standard", type="decimal", precision=16, scale=4, nullable=true)
     * @Assert\Expression(
     *     "this.getPriceFor2PaxStandard() != null or (this.getPriceFor2PaxStandard() == null and !this.isPriceForAccLevelRequired('standard'))",
     *     message="The price for 2 pax standard is required",
     *     groups={"agency_tripEdit_finalsave"}
     * )
     */
    private $priceFor2PaxStandard;

此外,在将asseriont用作属性级别时,如果我使用value而不是this.getPriceFor2PaxStandard()也不起作用.

In addition, does not work either if I use value instead of this.getPriceFor2PaxStandard() when using the asseriont as a attribute level.

任何提示将不胜感激:-)

Any hint would be appreciated :-)

推荐答案

这是symfony中的错误.如果查看ExpressionValidator的代码,您会看到它跳过验证值是否为null或空字符串.这对于其他一些约束很有用,但在ExpressionValidator中毫无意义.我刚刚提交了一个拉动请求来解决此问题.目前,最简单的方法是交换给回调验证器.

It is a bug in symfony. If you look at the code for the ExpressionValidator you can see it skips validating if the value is null or an empty string. This is useful for some other constraints but pointless in the ExpressionValidator. I have just submitted a pull request to fix it. The easiest way around this at the moment would be to swap to a callback validator.

<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class ExpressionValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof Expression) {
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression');
        }

        if (null === $value || '' === $value) {
            return;
        }

        //...
    }

    //...

}

这篇关于断言表达式验证在Symfony 2.4中的属性级别上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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