Search code examples
formssymfonyvalidationassert

Symfony 4 -- Form min max validation


How to be sure that min < max before validation

here my entity

/**
 * @var int
 *
 * @ORM\Column(name="min", type="integer", nullable=true)
 */
private $min;

/**
 * @var int
 *
 * @ORM\Column(name="max", type="integer", nullable=true)
 */
private $max;

in the form :

  ->add('min',               NumberType::class,array('required' => false))
  ->add('max',               NumberType::class,array('required' => false))

it's an option and min must be inferior to max before validating the form

How can i verify and send a message to the user to change his form if it's not correct.

Thanks


Solution

  • There are multiple ways to approach this that I can think of.

    1. The Callback-Constraint was already mentioned in the comments.
    2. Creating your own custom constraint
    3. Using the Expression-constraint

    Probably the latter is the easiest one. Basically it looks something like this:

    /**
     * @Assert\Type("integer")
     * @Assert\Expression("this.getMin() <= this.getMax()")
     */
    private $min;
    
    /**
     * @Assert\Type("integer")
     */
    private $max;
    

    See: https://symfony.com/doc/current/reference/constraints/Expression.html

    Creating a custom constraint is even more work than the Callback-constraint, so I won't go into details for that, but you can find a good article in the documentation.