Am checking validation of date using regex how it works for date but not for Year ? .Please help me to solve this issue.
Output :
false
true
false
true
Expected Output :
false
false
false
false
public static void main(String args[])
{
System.out.println(dateFormatValidate("ddMMyyyy","^(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[012])((19|20)\\d\\d)?", "08s21988"));
System.out.println(dateFormatValidate("ddMMyyyy","^(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[012])((19|20)\\d\\d)?", "08021s88"));
System.out.println(dateFormatValidate("ddMMyyyy","^(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[012])((19|20)\\d\\d)?", "s8021988"));
System.out.println(dateFormatValidate("ddMMyyyy","^(0?[1-9]|[12][0-9]|3[01])(0?[1-9]|1[012])((19|20)\\d\\d)?", "0802198s"));
}
public static boolean dateFormatValidate(String format, String regex, String value) {
try {
if (value != null && !"".equals(value.trim()) && format != null && !"".equals(format.trim()))
{
if ((regex != null && !"".equals(regex.trim()) && Pattern.matches(regex, value)) || regex != null || "".equals(regex))
{
SimpleDateFormat dformat = new SimpleDateFormat(format);
dformat.setLenient(false);
dformat.parse(value);
return true;
} else
return false;
} else
return false;
} catch (Exception e) {
return false;
}
}
org.apache.commons.lang.time.DateUtils#parseDateand catch the exceptionlenient=false, so the SimpleDateFormat should catch all invalid formats.formatorregexisnullor empty. They probably won’t be in practical use, since that would be a programming error. If you want to parse a date, you must provide a format.