Search code examples
symfonydoctrineentityassert

Assert\Range for integer doesn't work in Symfony


I want to validate an integer with Symfony\Component\Validator\Constraints to be in a special range.

Here is my code:

/**
 * @var integer
 * @Assert\Range(
 *      min = 120,
 *      max = 180,
 *      minMessage = "You must be at least 120 cm tall to enter",
 *      maxMessage = "You cannot be taller than 180 cm to enter"
 * )
 * @ORM\Column(name="cp",  type="integer", nullable=true)
 */
protected $cp;

But it doesn't work.

Some info:

  • This is in a custom UserEntity which extends BaseUser
  • Symfony version 2.8
  • I use easyAdminBundle to create/update/delete users
  • I already put use Symfony\Component\Validator\Constraints as Assert; at the top

Solution

  • You must use validate() method on the validator service.

    Also check is your validation enabled in framework config.

    When you want to persist new object you first validate them with ValidatorInterface instance method in your controller. If object is valid then persist them if not send user some info about error.

    Please check full tutorial about use of validator and other stuff symfony docs

    If you use easyAdminBundle in config you must for cp property add

    - { property: 'cp', type : 'integer', type_options: { attr : { min : minValue, max: maxValue }}}
    

    Check documentation how to setup configuration fo easy admin