Bernhard Schussek
Contributed by Bernhard Schussek in #11673

Comparing dates is one of the most frequently requested functionalities for the Symfony Validator component. That's why Symfony 2.6 will include date support for comparison and range constraints.

First, GreaterThan, GreaterThanOrEqual, LessThan and LessThanOrEqual constraints allow you to compare a value with the given date. Let's imagine that your application creates bookings that must be confirmed in 15 minutes or less. Using the LessThanOrEqual constraint, you can use the following code:

1
2
3
4
5
6
7
8
9
use Symfony\Component\Validator\Constraints as Assert;

class Booking
{
    /**
     * @Assert\LessThanOrEqual("+15 minutes")
     */
    protected $confirmedAt;
}

Another example would be to limit the access of your website to minors, which could be achieved as follows:

1
2
3
4
5
6
7
8
9
use Symfony\Component\Validator\Constraints as Assert;

class Person
{
    /**
     * @Assert\LessThan("-18 years")
     */
    protected $dateOfBirth;
}

These constraints support all of the semantic formats accepted by the DateTime constructor, so you can define pretty advanced validations. Consider an application that allows users to submit events, but restricted to those which start during the current year. Using the Range assert you could apply this validation as follows:

1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Validator\Constraints as Assert;

class Event
{
    /**
     * @Assert\Range(
     *     min = "first day of January",
     *     max = "first day of January next year"
     * )
     */
    protected $startDate;
}

Be aware that PHP will use the server's configured timezone to interpret these dates. If you want to set the timezone explicitly, append it to the date string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\LessThanOrEqual("+15 minutes Asia/Tokyo")
 */
protected $confirmedAt;

/**
 * @Assert\LessThan("-18 years UTC")
 */
protected $dateOfBirth;

/**
 * @Assert\Range(
 *     min = "first day of January America/Buenos_Aires",
 *     max = "first day of January next year America/Buenos_Aires"
 * )
 */
protected $startDate;

All the previous examples use annotations to set the validation, but you can also use YAML and XML validation files. Check out the Validator documentation to get more examples about these validators (as the time of writing this blog post, the documentation hasn't been merged; check it out at this pull request).

Lastly, if you want to use these date validators but you cannot upgrade your application to Symfony 2.6, check out the PUGXExtraValidatorBundle, which adds three similar validators called DateRange, MinDate and MaxDate.

Published in #Living on the edge