Reputation: 183
I need to add input validation for Dates entered by users. There is a startDate and endDate. The startDate needs to be current date or later. The endDate needs to be equal to OR after the startDate.
The date format i am using is YYYY-MM-dd
Already validating that the date is a proper date
In the request class we currently are using javax.validation like this:
@Pattern(regex = CommmonRegexp.DATE, message = "INVALID_FIELD")
How do i edit this to fit my needed constraints?
What i need: validate input for both dates making sure startDate only accepts current date or later, and endDate accepts only dates later than startDate
Upvotes: 3
Views: 6438
Reputation: 976
You should use java.time
to operate on dates in java. Following is a working method to validate the date as you require. You can change the format as you require. There are a bunch of other useful methods that you can use.
call this method as validateDates("2019-03-03","2019-04-03")
public static boolean validateDates(String start, String end) {
try {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(start, dateFormat);
LocalDate endDate = LocalDate.parse(end, dateFormat);
LocalDate current = LocalDate.now();
return (startDate.isEqual(current) || startDate.isAfter(current)) && endDate.isAfter(startDate);
}catch(DateTimeParseException ex) {
ex.printStackTrace();
}
return false;
}
UPDATE
You can use predefined or custom DateTimeFormatter
s as per your need. You can go through this JavaDoc for details on DateTimeFormatters in detail and through this blog for examples.
This and this are some good-reads about how to use zone-ids with date-times.
Upvotes: 4
Reputation: 248
You should probably use something like the java 8's LocalDate class rather than regex. It has plenty of helper methods to do what you are looking for:
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
Upvotes: 0