Java RegEx – Validate dd/mm/yyyy & mm/dd/yyyy Date Format

Java RegEx – Validate dd/mm/yyyy Date Format example shows how to validate date in dd/mm/yyyy, dd-mm-yyyy, or mm/dd/yyyy format using regular expression.

How to validate dd/mm/yyyy date format using regex in Java?

The structure of the date in the format “dd/mm/yyyy” needs to have 2 digits as day followed by /, followed by 2 digits for the month followed by /, and then 4 digits for the year. Let’s try to come up with a simple regex to validate this.

Here is the basic version of the same.

Where,

Let’s try our regular expression against some dates.

Output

It looks like it is working for a basic test scenario. However, what about the date “45-15-2001”? Our regex will consider this date as a valid date because syntax-wise it is still valid even though the day cannot be greater than 31 and the month cannot be greater than 12.

Let’s include these additional rules in our regex. Here is the updated regular expression.

This regex is divided into 3 parts. The first part is for the day. Which says,

This regex allows us to have days from 01 to 31. The second part is for the month.

This allows us to have the month from 01 to 12. The third, year part is simply “\\d{4}”, which says any 4 digits. All three parts are connected using “/” to make the date in the format “dd/mm/yyyy”. Let’s test the new regex.

Output

As you can see from the output, it worked as expected. It rejected the dates having the day greater than 31 or less than 1. It also rejected the month greater than 12 and less than 1.

Important Note:

Even though the date is in a valid format as per the above regex, it does not mean that the actual date is valid. For example, the format of the date “30/02/2001” is valid, but the actual date is not because February month cannot have day 30.

In order to do that, we need to actually parse the date after it is validated by the regex as given below.

Output

How to validate mm/dd/yyyy date format using regex in Java?

In the above code replace the pattern with this one.

You can rearrange the day, month, and year parts to suit your needs. If you want more formats, please visit the java regex validate date example.

This example is part of the Java RegEx tutorial with examples.

Please let me know your thoughts in the comment section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *