Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation for optional properties in Symfony

Tags:

php

symfony

I love to use the Validation annotations in Symfony with my huge entity model like so:

/**
 * @var string
 * @ORM\Column(type="string", length=255, nullable=false, name="name")
 *
 * @Assert\NotBlank(message="Name must not be empty")
 * @Assert\Length(min=2, minMessage="Name must be at least 2 characters long",max=255, maxMessage="Name must not be longer than 255 characters")
 */
private $name;

This will ensure that "name" is never null, blank or has <2 or > 255 chars.

But how to achieve this when let's say there's a similar field like description for which the same rules apply but it's an optional property?

I know that I can write Callback functions, having custom constraints and so on... but this will force me to create my own logic for all existing Validators (NotBlank, Length, Number, Valid a.s.o).

I'd look for something similar like:

/**
 * @var string
 * @ORM\Column(type="string", length=255, nullable=true, name="description")
 *
 * @OptionalAssert\NotBlank(message="Name must not be empty")
 * @OptionalAssert\Length(min=2, minMessage="Name must be at least 2 characters long",max=255, maxMessage="Name must not be longer than 255 characters")
 */
private $description;

So description can be null but if it's not null then it must not be blank and must have > 2 or < 255 chars.

I thought of creating a custom constraint for that - but I am able somehow to hand over the standard validators and there parameters to my custom validator to avoid recreating \NotBlank \Length etc. all on my own and just reusing the standard ones?

Thanks

like image 799
LBA Avatar asked Oct 19 '22 05:10

LBA


1 Answers

I think you're missing @Assert/NotNull() on the first one, the second one I think would be fine minus the Optional part of the @Assert() since @Assert/NotNull() is not included. NotBlank() and Length(min) will not enforce NotNull().

So you would have something like this for name:

/**
 * @var string
 * @ORM\Column(type="string", length=255, nullable=false, name="name")
 *
 * @Assert\NotNull(message="Name must not be empty")
 * @Assert\NotBlank(message="Name must not be empty")
 * @Assert\Length(min=2, minMessage="Name must be at least 2 characters long",max=255, maxMessage="Name must not be longer than 255 characters")
 */
private $name;

And minus the @Assert/NotNull() for the description:

/**
 * @var string
 * @ORM\Column(type="string", length=255, nullable=true, name="description")
 * 
 * @Assert\NotBlank(message="Name must not be empty")
 * @Assert\Length(min=2, minMessage="Name must be at least 2 characters long",max=255, maxMessage="Name must not be longer than 255 characters")
 */
private $description;
like image 163
Jared Farrish Avatar answered Oct 22 '22 01:10

Jared Farrish