Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Date validation?

 
M Burke
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to valid a date entered by a user on a form. Its a free flowing text field so it can be any number of formats. So I cannot easly pick out the year, month, & day fields. So I can not set a Calander object.

I have the part that tests if the format is valid. But then I need to test to see if the date itself is valid like... 33 sept 07 is bad, 07/66/2007 is bad.

Here is what I have so far...

if(priceBeginDate != null && priceBeginDateStatus == true){
try {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.setLenient(false);
Date dt2 = df.parse(priceBeginDate);
}
catch (ParseException e) {
errors. add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.grid.ui.priceBeginDate"));
priceBeginDateStatus = false;
}
catch (IllegalArgumentException e) {
errors. add(ActionErrors.GLOBAL_MESSAGE, new ActionError("errors.grid.ui.priceBeginDate"));
priceBeginDateStatus = false;
}
[ October 13, 2007: Message edited by: M Burke ]
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, what format does the entered string have to have exactly - or is that not specified, and does the computer have to intelligently parse the entered text and make a Date out of it?

The second is very hard, for example what if the user enters "08/09/2007" - there is no way for the computer to know if that means 9 August or 8 September 2007.

By using DateFormat.SHORT as you did in your code, DateFormat.parse(...) will accept some things but not everything, and what the parse(...) method does and does not accept exactly isn't clearly specified in the Java API documentation.

It's easier to change the design your application: instead of one free-format text field, use separate fields for the date, month and year (and time if necessary) - that will be much easier to parse for the computer.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or use a JSpinner with a SpinnerDateModel, and a dateformat:

This allows you to scroll through all fields by selecting only part of the date, or fill in a date. If the filled in date is invalid it is ignored and the previous value is used.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic