Symfony 表单验证约束表达式 [英] Symfony Form Validation Constraint Expression

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

问题描述

我有表单,需要创建内联验证:

I have form, and need to create inline validation:

$builder
        ->add('Count1', 'integer', [
            'data'        => 1,
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])
        ->add('Count2', 'integer', [
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])
        ->add('Count3', 'integer', [
            'data'        => 0,
            'constraints' => [
                new NotBlank(),
                new NotNull(),
            ],
        ])

如何对规则进行白内联验证表达式

How white inline validation Expression for rules

  1. Count2 >=Count1
  2. Count3 <=Count2
  3. Count2 >= $someVariable

推荐答案

使用 表达式约束 适用于情况 1 和 2.

Other solution by using Expression Constraint for cases 1 and 2.

use Symfony\Component\Validator\Constraints as Assert;

// ...

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'constraints' => [
            new Assert\Expression([
                'expression' => 'value["Count2"] >= value["Count1"]',
                'message' => 'count2 must be greater than or equal to count1'
            ]),
            new Assert\Expression([
                'expression' => 'value["Count3"] <= value["Count2"]',
                'message' => 'count3 must be less than or equal to count2'
            ]),
        ],
    ]);
}

对于情况 3,您可以直接在 Count2 字段上使用 Assert\GreaterThanOrEqual 约束.

For case 3 you can use Assert\GreaterThanOrEqual constraint directly on Count2 field.

我猜你的表单没有绑定对象模型,否则阅读 引用的文档就足够了,而且更好,因为您可以直接在属性上使用这些表达式.

I guess your form doesn't have a binding object model, otherwise to read the documentation referred is enough and better because you could use these expression on your properties directly.

这篇关于Symfony 表单验证约束表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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