Leo
Leo

Reputation: 5235

Regex for date validation

I am using the following regex to validate a date in java:

"^(0?[1-9]|[12][0-9]|3[01])[-./](0?[1-9]|1[012])[-./]((19|20)\\d\\d)$"

But it is also taking the the formats like 21-12.2014 or 21.12/2014 as valid date. I know that this is because I used [-./] in my regex. How can I avoid this problem?

Upvotes: 0

Views: 87

Answers (2)

Ian McLaird
Ian McLaird

Reputation: 5585

Don't use a regex at all. Just parse the date, since you're obviously about to do that anyway.

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(dateStr.replaceAll("[./]", "-"));

Catch the exception for the invalid date.

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Here you need to use back-reference.

"^(0?[1-9]|[12][0-9]|3[01])([-./])(0?[1-9]|1[012])\\2((19|20)\\d\\d)$"

\\2 in the above regex refers to the characters present inside the group index 2.

NOTE: Don't parse dates with regex.

Example:

String s1 = "21-12-2014";
String s2 = "21-12/2014";
System.out.println(s1.matches("^(0?[1-9]|[12][0-9]|3[01])([-./])(0?[1-9]|1[012])\\2((19|20)\\d\\d)$"));
System.out.println(s2.matches("^(0?[1-9]|[12][0-9]|3[01])([-./])(0?[1-9]|1[012])\\2((19|20)\\d\\d)$"));

Output:

true
false

Upvotes: 2

Related Questions