Jsf - date validation with expression language

I need to check the value of my parent's input field. There must be a few possibilities: dd.MM.yyyy

, dd.M.yyyy

, d.MM.yyyy

, d.m.yyyy

, and dd.MM.yy

, dd.M.yy

, d.MM.yy

, d.m.yy

. For example, you can enter 03/07/1993, 7.3.93 or whatever.

The following regex example just checks the format check, but does not check if a date exists (e.g. 02/29/2011 or 02/47/2011)

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 greater than 12 and the day is greater than 31. I think I should use a 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})$";

      

+3


source to share


2 answers


If the regex is optional, you can try converting your string to a date using the method parse

java.text.SimpleDateFormat

and see if it succeeds.

If so (you are getting a valid object Date

), you have a valid date entered in your form (or input). If that fails, the function parse

returns null

and the String

input entered is invalid.



Here's the javadoc for the method parse

.

EDIT: For additional verification in case you don't want to use setLenient

, you can use Date

which you get from parse

and convert it back to String

using the same format. Then just compare String

the result of the transformation with the one you supply as input. If they match, you have valid input.

+2


source


You can split it to get day and month details.

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 validation with a field Calendar.MONTH

.

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

0


source







All Articles