I need to check the value of my birthdate input field. There should be several possibilities: dd.MM.yyyy, dd.M.yyyy, d.MM.yyyy, d.m.yyyy and also dd.MM.yy, dd.M.yy, d.MM.yy, d.m.yy. For example you can input 07.03.1993, 7.3.93 or whatever.
The following regex example just checks the format validation, but it doesn't check if the date exists (e.g. 29.02.2011 or 47.02.2011 will be allowed)
String s = (String) arg2;
String pattern = "^(\\d{2}|\\d{1})\\.(\\d{2}|\\d{1})\\.(\\d{2}|\\d{4})$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(("date correct"));
} else {
System.out.println("date incorrect");
}
edit: I just created the following regex statement, now it checks if the month is bigger than 12 and the day is bigger than 31. I think I should use regex first and then validate the date with SimpleDateFormat
String s = "^((0?[1-9]|[12][0-9]|3[01])\\.(0?[1-9]|1[012])\\.((19|20)\\d{2})$";
If regex is not a must, you can try and convert your string to a date using the parse method of java.text.SimpleDateFormat and see if it succeeds.
If it does (you get a valid Date object), you have a valid date entered in your form (or input). If it does not succeed, the parse function returns null and the String you input was invalid.
Here's the javadoc for the parse method.
EDIT: For the extra validation in case you don't want to use setLenient, you can use the Date that you get from parse and convert it back to a String using the same format. Then just compare the String resulting from the conversion with the one you supply as input. If they match, you've got valid input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With