This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
If I have 3 select boxes in a jsp each for month, day and year that allow the user to select a date, how can I verify that they do not select Feb 30 2003? I guess this basically comes to the question, how do I verify that a date is valid? I'm not worried about filtering the options in the select, just the date validation.
Instantiate a GregorianCalendar with the selected year, month, and date. If the date is not valid, GregorianCalendar will adjust them to a valid date. Take a look at this code:
If you run this you will see that MONTH = 2 (March) and DAY_OF_MONTH = 2. In other words, GregorianCalendar adjusted your invalid input date of 2/30/2003 to 3/2/2003. So now all you have to do to check to see if a date is valid is check what was input (2/30/2003) versus what you get back from calls to calendar.get(). If they are the same, your date is valid. If they are different, your date is invalid. You might do something like this:
[ September 30, 2003: Message edited by: Jason Menard ]
You might consider using the "java.util.Calendar" class. It has a method, "setLenient(boolean b)" that indicates whether the input interpretation should be lenient or not. Something like this:
If you run this, you'll notice that the first calendar manipulation will work, but the second will throw an exception. So do the second, enclose it with a try/catch block, and if you end up in the "catch" block you know that the user gave you bad data.