Symfony validators, a tool little used

Im talking on self experience, maybe im the only one that use this amazing tool so little. But i recently i propose my self to change that and integrate it on my forms.

There are a lot of build in validators but how we can combine them and end up with a powerful validation constraints is up to us.

One of them that kept my attention and is the reason of writing this post is the CallbackValidator.

The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you’re using validation with forms, this means that you can make these custom errors display next to a specific field, instead of simply at the top of your form.

My requirement at the time was to validate and restrict two date time fields of my form called startDate and endDate respectively. The endDate as suppose cant be set to a date before the startDate field., so enter CallbackValidator

->add('startDate', DateType::class, array(
    'widget' => 'single_text',
    'format' => 'yyyy/MM/dd',
    'constraints' => array(
        new NotBlank(),
        new DateTime(array(
            'format' => 'Y/m/d'
        ))
    )
))
->add('endDate', DateType::class, array(
    'widget' => 'single_text',
    'format' => 'yyyy/MM/dd',
    'constraints' => array(
        new DateTime(array(
            'format' => 'Y/m/d'
        )),
        new Callback(array(
            'callback' => function (\DateTime $endDate, ExecutionContextInterface $context) {
                $startDate = $context->getRoot()->get('startYear')->getData();
                if ($startDate > $endDate) {
                    $context->buildViolation('End date cant be before start date.')
                        ->atPath('endDate')
                        ->addViolation();
                }
            }
        ))
    )
));

Just as easy as that my requirements where fulfilled.

So my advice is, and to my self; please use validators.

Advertisements

One Comment

  1. A few pointers:
    – If you had a DTO class (maybe a Doctrine embeddable), you could also use an expression, such as @Assert\Expression(“value false on the optional field.
    – You should nickname the Symfony\Component\Validator\Constraints namespace as Assert to avoid accidents with \DateTime.

    Liked by 1 person

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s