I’m having trouble validating a value to allow NULL but not an empty string with the Symfony2 validator component.
I’ve integrated the component in a Silex application and used the Property Constraint target to validate some properties of my Application Entities (not a Doctrine Entity).
I’ve added this static method to my Entity class to validate name and service_id on my Entity, problem is that when service_id is NULL which should be valid the NotBlank constraint kicks in and reports a violation.
static public function loadValidatorMetadata(ClassMetadata $metadata)
{
// name should never be NULL or a blank string
$metadata->addPropertyConstraint('name', new Assert\NotNull());
$metadata->addPropertyConstraint('name', new Assert\NotBlank());
// service_id should either be a non-blank string or NULL
$metadata->addPropertyConstraint('service_id', new Assert\NotBlank());
}
Bottomline, I’m looking how to allow either a String or NULL as service_id but not allow an empty string.
PS: I’ve also tried the MinLength(1) constraint but that allows empty strings unfortunately.
The
NotBlankconstraint treatsnullas a blank value, as can be seen in this test.When using doctrine, this can be solved by using the Valid constraint. If the value of the field is not
null, it will attempt to validate it.Since you are not using doctrine entities, you’ll probably have to use a callback validator or write your own constraint.
EDIT
To answer your new question on adding a callback constraint as a property constraint: No, it is not possible to do that.
The callback constraint acts on the whole object, not just a single property. Here’s an example of how you can use the callback constraint: