0

I'm creating a program and for part of it, the user must enter the date in the format "MM/DD/2008". I already have the pieces in place to take the month and date separately but how do I make sure that they entered it correctly and not "M/D/2008" or a letter?

Here's the case that asks for the input...

System.out.print("Please enter a date to view (MM/DD/2008, 0 to Quit):\n");
            String dateChoice = scan.next();
            while (!dateChoice.equals("0")) {
                String[] tokens = dateChoice.split("/");
                int month = Integer.parseInt(tokens[0]) - 1;
                int date = Integer.parseInt(tokens[1]) - 1;
                choice.weatherRecord(month, date);
                System.out.print("Please enter a date to view (MM/DD/2008, 0 to Quit):\n");

                dateChoice = scan.next();
            }
Ryan Dorman
  • 317
  • 1
  • 3
  • 10
  • To make it more convenient ask the user to enter the date and you can further validate the date by using the regex. For regex to validate date format you can check my answer :https://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy/26972181#26972181 This validates almost most of the date formats. – Alok Chaudhary Apr 13 '15 at 05:41

1 Answers1

1

You can actually use JFormattedTextField like this:

JTextField jtf = new JFormattedTextField(new SimpleDateFormat(formatString));

This would create a textfield that only allows input matching formatString.

  • So for this example, I would type JTextField jtf = new JFormattedTextField(new SimpleDateFormat("00/00/2008")); ? How can I make it so the user can enter again if its incorrect? – Ryan Dorman Apr 13 '15 at 05:20
  • 1
    nearly. you should take a closer look at this: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html . your format would allow any value <100, since "DD" means "day in year". you should use "dd" instead. –  Apr 13 '15 at 05:23
  • how would this work? JTextField jtf = new JFormattedTextField(new SimpleDateFormat("00/00/2008")); My only concern would be that the user won't have a chance to enter again if they type it in wrong once. – Ryan Dorman Apr 13 '15 at 05:24
  • 00/00/2008 shouldn't be a valid date, so it won't ever validate. Actually, you can enter anything into the field, but the most recent **valid** entry will be returned by `getValue()`. The user can edit as long as he wants (and you let him do so). –  Apr 13 '15 at 05:30
  • Hmmmm... For some reason I'm still confused... – Ryan Dorman Apr 13 '15 at 05:44