gpt4 book ai didi

validation - 断言表达式验证在 Symfony 2.4 中的属性级别不起作用

转载 作者:行者123 更新时间:2023-12-03 17:53:34 25 4
gpt4 key购买 nike

我正在尝试通过 @Assert\Expression ( http://symfony.com/doc/2.4/reference/constraints/Expression.html ) 在字段级别验证属性。

它使用以下代码在类级别工作:

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

但是如果我在属性级别使用相同的代码(应该没问题),则不起作用:
/**
* @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;

此外,如果我使用 value 也不起作用而不是 this.getPriceFor2PaxStandard()当使用断言作为属性级别时。

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

最佳答案

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

<?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;
}

//...
}

//...

}

关于validation - 断言表达式验证在 Symfony 2.4 中的属性级别不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com