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
@Assert/NotNull()
on the first one, the second one I think would be fine minus theOptional
part of the@Assert()
since@Assert/NotNull()
is not included.NotBlank()
andLength(min)
will not enforceNotNull()
. – Jared Farrish