Validate a Date in Java

In this post, we will discuss various ways to validate a date in Java.

 

1. Using OWASP Validator

We can use OWASP Validation to check for a Date in US format which is very secure and extends support for leap years. It provides below regular expression:

 
^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

 

Download   Run Code

Output:

01/13/2010 is valid
1/13/2010 is valid
1-13-2010 is valid
1/13/00 is valid
02/29/2016 is valid
02/29/2015 isn’t valid

 

2. Using Apache Commons Date Validator

We can use any of the following methods provided by Apache Commons DateValidator to validate a date:

boolean isValid(value)
boolean isValid(value, pattern)
boolean isValid(value, Locale)
boolean isValid(value, pattern, Locale)

 

Download

Output:

01/12/2010 is valid
1/13/2010 is valid
1-13-2010 isn’t valid
02/29/2016 is valid
02/29/2015 isn’t valid

 
Similarly we can use one of the following methods to validate a date and convert it to java.util.Date:

Date validate(value)
Date validate(value, pattern)
Date validate(value, Locale)
Date validate(value, pattern, Locale)

 

Download

Output:

01/13/2010 is valid
1/13/2010 is valid
1-13-2010 isn’t valid
02/29/2016 is valid
02/31/2015 isn’t valid

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of