Symfony Form Validation: Validating a date range

One of the (Symfony based) PHP projects I’m working on contains a form which allows the user to generate video clips from CCTV footage. To do this the user can enter a start and stop DateTime. For this to work the submitted input data is then checked: both start and stop must be dates, and the stop date must be set to a point in time after the start date.

Symfony’s DateTime Constraint can make sure both entries are DateTime instances. To check whether that the end date is after the begin date, one can use the Callback Constraint. Injected into that callback is a ExecutionContextInterface by which you can access the form, and thus other form params.

Here’s an example with the inputs start and stop:

use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

// …

$builder
    ->add('start', 'datetime', 
        'constraints' => [
            new Constraints\NotBlank(),
            new Constraints\DateTime(),
        ],
    ])
    ->add('stop', 'datetime', [
        'constraints' => [
            new Constraints\NotBlank(),
            new Constraints\DateTime(),
            new Constraints\Callback(function($object, ExecutionContextInterface $context) {
                $start = $context->getRoot()->getData()['start'];
                $stop = $object;

                if (is_a($start, \DateTime::class) && is_a($stop, \DateTime::class)) {
                    if ($stop->format('U') - $start->format('U') < 0) {
                        $context
                            ->buildViolation('Stop must be after start')
                            ->addViolation();
                    }
                }
            }),
        ],
    ]);

If you want to have a minimum duration between both start and stop, you can change the number 0 in the snippet above to any number of seconds.

Did this help you out? Like what you see?
Thank me with a coffee.

I don't do this for profit but a small one-time donation would always put a smile on my face. Thanks!

☕️ Buy me a Coffee (€3)

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.