I found the regular expression for MM/DD/YYYY at http://www.regular-expressions.info/regexbuddy/datemmddyyyy.html but I don\'t think I am using it correctly.
Here\'s
Regex of the author of the question is almost correct. Date is not validated because a pattern should be:
pattern="^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\d\d$"
or if to be fancy:
pattern="^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
Please note that this pattern checks only for a format of a date and max/min values for individual date elements. That means a user's entry should be checked for validity of date in JavaScript function and/or a Server (e.g February 29 should not be allowed if a year is not a leap one).
As a side note, if you would like to allow a single digit (let's say for a month), change a month part to
([0-9]|0[1-9]|1[012])
Explanation:
[0-9] - single digit between 0 and 9
or
0[1-9] - two digits between 01 and 09
or
1[012] - two digits limited to 10, 11, 12
Your regex needs delimiters:
/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/
String timeStamp = "03/11/2018 17:51:45";
private static Pattern TIMESTAMP_PATTERN = Pattern.compile("(0?[1-9]|1[012])/(0?[1-9]|[1-2][0-9]|3[0-1])/" + "([1-9][0-9]{3}) ([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9])");
private static boolean isTimeStampValid(String timeStamp) {
boolean isFeb = timeStamp.split("/")[0].matches("(0?[2])");
if (isFeb) {
boolean isValidFebDate = timeStamp.split("/")[1].matches("(0?[1-9]|1[1-9]|2[0-8])");
if (!isValidFebDate) return false;
}
return TIMESTAMP_PATTERN.matcher(timeStamp).matches();
}