aspose file tools*
The moose likes Java in General and the fly likes Date validation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Date validation?" Watch "Date validation?" New topic
Author

Date validation?

M Burke
Ranch Hand

Joined: Jun 25, 2004
Posts: 388
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

Joined: Aug 16, 2005
Posts: 14347
    
  22

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Date validation?