Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with validating a date

I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".

Why does the line newDate = dateFormat.parse(date); not catch that?

// checks to see if the document date entered is valid
    private String isValidDate(String date) {

        // set the date format as mm/dd/yyyy
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date newDate = null;

        // make sure the date is in the correct format..        
        if(!date.equals("mm/dd/yyyy")) {
            try {
                newDate = dateFormat.parse(date);
            } catch(ParseException e) {
                return "The Document Date needs to be in the format MM/DD/YYYY\n";
            }

            // make sure the date is a valid date..
            if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
                return "The Document Date is not a valid date\n";
            }

            return "true";
        } else {
            return "- Document Date\n";
        }
    }

EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?

like image 421
Catfish Avatar asked Jun 13 '26 08:06

Catfish


1 Answers

As already mentioned, the SimpleDateFormat is able to parse "2/2/2011" as if it is "02/02/2011". so no ParseException is thrown.

On the other hand, dateFormat.format(newDate) will return "02/02/2011" and is compared against "2/2/2011". The two strings aren't equal, so the second error message is returned.

setLenient(false) will not work in this case:

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

(source: java docs)

you can use a regular expression to manually check the string format:

if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}
like image 132
MarioP Avatar answered Jun 15 '26 21:06

MarioP