Validating Dates
Learn how to validate date values in the past and in a specific format.
We'll cover the following
In this lesson, we will show how to validate a date field. Say, we want to store the date when the player won the last title. We will add a field lastWon
to the Athlete
class. This value must be in the past and must follow a specific pattern (dd-mm-yyyy). Any date value violating these constraints should result in a validation error. We will use @Past
and @DateTimeFormat
to validate the date field.
@Past
We will create a Date
field lastWon
and generate getter and setter methods. Then, we will use the @Past
annotation with an appropriate error message as follows:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.