This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes date validation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "date validation" Watch "date validation" New topic

date validation

Eric Sexton
Ranch Hand

Joined: Sep 12, 2003
Posts: 133
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.
Jason Menard

Joined: Nov 09, 2000
Posts: 6450
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 ]
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
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.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
One option might be a date picker - I have one on a website you can have a look at
Date Picker
I agree. Here's the link:
subject: date validation
It's not a secret anymore!