Symfony表单验证约束表达式

Iva*_*nko 2 validation symfony-forms symfony symfony-validator

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

$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(),
            ],
        ])
Run Code Online (Sandbox Code Playgroud)

白色内联验证如何表达规则

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

yce*_*uto 7

通过对案例1和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'
            ]),
        ],
    ]);
}
Run Code Online (Sandbox Code Playgroud)

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

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