Search code examples
validationsymfonysymfony-formssymfony-validator

Symfony Form Validation Constraint Expression


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

Solution

  • 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'
                ]),
            ],
        ]);
    }
    

    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.