【问题标题】:Assert Expression validation not working at attribute level in Symfony 2.4断言表达式验证在 Symfony 2.4 中的属性级别不起作用
【发布时间】:2014-08-30 05:52:24
【问题描述】:

我正在尝试通过@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(),也不起作用。

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

【问题讨论】:

    标签: validation symfony assert


    【解决方案1】:

    这是 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;
            }
    
            //...
        }
    
        //...
    
    }
    

    【讨论】:

    • 谢谢汤姆!我仍然使用表达式语言进行验证,但在类级别上,什么工作正常。只是我想有一个更清晰的代码。
    • 看起来 PR 已被合并,该问题本应从 2.6 开始修复,对吧 @Tom Corrigan? github.com/symfony/symfony/pull/11709 但是如果属性/值为空,我的表达式仍然不会被触发:/** @Assert\Expression("this.getLoggiaHandrail() == '1' and value != null) */ $loggiaHandRailMaterial;
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 2017-02-27
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多