Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

date validation

 
Eric Sexton
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 6450
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One option might be a date picker - I have one on a website you can have a look at
Date Picker
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic