当前位置: 动力学知识库 > 问答 > 编程问答 >

java - jsf - validate date with expression language

问题描述:

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.

网友答案:

You can split it to get day and month parts of the date.

Then you can do something like:

final int dayToCheck = 32; // user input
final int month = 2; // user input
final int year = 1981; // user input        

final Calendar cal = Calendar.getInstance();
cal.set(year, month, 1); // day doesn't need to be the user input, it can be any day in the month you want to check

if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) > dayToCheck) {

    // the day is invalid
}
if (cal.getActualMinimum(Calendar.DAY_OF_MONTH) < dayToCheck) {

    // again, the day is invalid
}

You can do the same check with the Calendar.MONTH field.

I haven't checked if this compiles, but you should get the idea.

分享给朋友:
您可能感兴趣的文章:
随机阅读: