3
votes

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

2
Since you tagged your question simpledateformat, I recommend you don’t use SimpleDateFormat. That class is notoriously troublesome and long outdated. And since your format is the default ISO 8601 for a LocalDate from java.time, the modern Java date and time API, use that class, and you don’t need any explicit formatter. - Ole V.V.
you can check a string representing a date for boundaries in dates with a regexp, but any regexp that does it well is far from the scope of a book on regexps. And the same happens to numbers. Better parse the date with SimpleDateFormat, then check for boundaries with proper methods. - Luis Colorado

2 Answers

4
votes

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 DateTimeFormatters 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.

0
votes

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