validation - Symfony 表单验证约束表达式

标签 validation symfony symfony-forms 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(),
            ],
        ])

规则的白色内联验证表达式
  • 计数 2 >=计数 1
  • 计数3 <=计数2
  • Count2 >= $someVariable
  • 最佳答案

    使用 Expression Constraint 的其他解决方案对于情况 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'
                ]),
            ],
        ]);
    }
    

    对于情况 3,您可以使用 Assert\GreaterThanOrEqual直接约束 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.

    关于validation - Symfony 表单验证约束表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40287266/

    相关文章:

    php - Symfony3类继承和数据库关系

    php - 强制不需要字段

    交响乐团 2.0 : How to validate embedded collection of forms without an entity

    validation - 关于在一个字段上使用 FacesValidator(JSF 验证)和 Bean 验证的问题

    javascript - form.$error.required 和 form.$invalid 的冲突验证

    CSS 验证问题

    php - 使用自定义验证约束检查数据库中是否存在条目

    validation - 第一次失败时停止 Fluent 验证

    php - Symfony 3 路由允许在占位符值中使用连字符/破折号

    symfony - 在 Symfony 2/Doctrine 2 中使用 MappedSuperclass 字段不持久?