Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3105

New in Symfony 2.6: Date support for Validator constraints

$
0
0
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
useSymfony\Component\Validator\ConstraintsasAssert;classBooking{/**     * @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
useSymfony\Component\Validator\ConstraintsasAssert;classPerson{/**     * @Assert\LessThan("-18 years")     */protected$dateOfBirth;}

These constraints support all of the semantic formats accepted by theDateTime 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
useSymfony\Component\Validator\ConstraintsasAssert;classEvent{/**     * @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
useSymfony\Component\Validator\ConstraintsasAssert;/** * @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.


Be trained by Symfony experts - 2014-10-06 Cologne - 2014-10-06 Cologne - 2014-10-08 Cologne

Viewing all articles
Browse latest Browse all 3105

Trending Articles