Java regex to check invalid dates

In previous tutorial, we learned about validating dates in different formats with/without requiring leading zeros. But that solve only part of problem i.e. validate date format structure in user input. It does not validate if the given date is invalid all together e.g. 31 Feb 2011. In this tutorial, we will learn to use java regex to create named groups so that we can later on validate the date itself. This solution uses a simple regex that merely captures groups of numbers that look like a month/day/year combination, and then use procedural code to check whether the date is correct. The main benefit of this method is that you can easily add additional restrictions, such as limiting dates to certain periods.

Regex with Named Groups

The solution requires use of named groups so let’s create them as below example:

Regex : ^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$

In above regex, we have captured 3 groups separated with forward slash (/) and they represent the month, day and year part in that sequence. Let’s also see a sample program which uses these named groups to check if it is a valid date or not.

List dates = new ArrayList();

dates.add("02/31/2011");  //Invalid date
dates.add("02/27/2011");  //Valid date

String regex = "^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$";

Pattern pattern = Pattern.compile(regex);

for (String date : dates)
{
Matcher matcher = pattern.matcher(date);
matcher.matches();

//Get date parts here
String day = matcher.group(2);
String month = matcher.group(1);
String year = matcher.group(3);

String formattedDate = month + "/" + day + "/" + year;

System.out.println("Date to check : " + formattedDate);
System.out.println("Is date valid : " + isDateValid(formattedDate));
System.out.println();
}

Output:

Date to check : 02/31/2011
Is date valid : false

Date to check : 02/27/2011
Parsed Date : Sun Feb 27 00:00:00 IST 2011
Is date valid : true

Please note that I am using below function to validate the correct date.

final static String DATE_FORMAT = "MM/dd/yyyy";

public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
Date d = df.parse(date);

System.out.println("Parsed Date : " + d);
return true;
} catch (ParseException e) {
return false;
}
}

There can be many variations in above regex as well as code to validate the date itself. Free free to play with code and write your own variations. It could be great if you could share them as well .. 🙂 Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.