13 Replies Latest reply: Jan 4, 2007 11:58 AM by 807607 RSS

    date validation

    807607
      Hi

      I'm writing some code for a college assignment and part of it has users inputing a date of birth to a text box. the code should them check to see if this is a valid date.

      here's what I have so far



      /*

      enter date

      */

      import javax.swing.JOptionPane; // import class JOptionPane

      public class checkDOB
      {
      public static void main (String args[])
      {
           boolean valid = false;
                String validDOB = "";


                while (valid == false)
                {
      String inputDOB = JOptionPane.showInputDialog( "Please Enter your date of birth in the format dd/mm/yyyy" );
      if (inputDOB.length() >= 8 && inputDOB.length() <=10)

                          {
                                    validDOB = inputDOB;
                                    valid = true;
                                    break;

                          }


                     else
                          {
                     JOptionPane.showMessageDialog(
                          null, "The Date you entered " + inputDOB + " is invalid, please try again", " Too Long", JOptionPane.PLAIN_MESSAGE );
                          }

                     }
                     JOptionPane.showMessageDialog(
                          null, "You date of birth is " + validDOB , " date", JOptionPane.PLAIN_MESSAGE );
      }

      }

      any help appreciated
        • 1. Re: date validation
          807607
               public static void main(String[] args) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
                    Date bdate = null;
                    Scanner in = new Scanner(System.in);
                    
                    System.out.println("Enter your DOB in dd/mm/yyy format:");
                    
                    while(true)
                    {
                         String dob = in.nextLine();
                         try
                         {
                              bdate = dateFormat.parse(dob);
                              break;
                         }
                         catch(ParseException e)
                         {
                              System.out.println("You Idiot! Put in the date in the correct format!");
                         }
                    }
                    
                    System.out.println("DOB = " + bdate);
               
               }
          Of course, you may want to put a sanity check in as well, just to make sur ethe date makes sense, since you can put in any numbers and it will parse as a date as long as the format matches.

          ~Tim
          • 2. Re: date validation
            796440
            What specific problem are you having?

            If you want to (or have to) roll your own validator, you'll want to check that the third and sixth characters are / (if you're requiring "02/02" for Feb. 2, rather than "2/2", else more complex checking), that all the other characters are digits, that the first two represent a number between 1 and 12, etc.

            Or, you could use SimpleDateFormat.

            Formatting a Date Using a Custom Format
            Parsing a Date Using a Custom Format
            • 3. Re: date validation
              807607
              Ok let me see if I've got this straight.

              You want to input the date as a String and determine if it is a valid date.

              issues you are likely to run into are

              1. Date formatting varies widely. 20070104, 04 JAN 2007, 01/04/2007 are all valid dates.
              2. The validation doesn't actually require that you make a date out of it, only that it have the correct elements and that those elements fall within ranges that you establish.

              Start by collecting the date String from the user. You're doing that already with the JOptionPane.

              You'll want to use the DateFormat class to do your date parsing it will also handle the validation up to a point.

              Follow the bouncing link to the api

              http://java.sun.com/j2se/1.4.2/docs/api/java/text/DateFormat.html

              This should get you where you need to go.

              Hope this helps,

              PS.
              • 4. Re: date validation
                807607
                Thought I'd toss this in just for information's sake
                    public static Date parseDate(String inDate, String pattern) throws ParseException
                    {
                        SimpleDateFormat f = new SimpleDateFormat(pattern) ;
                        return f.parse(inDate) ;
                    }
                A very basic method to parse a date from a string. if the date isn't a valid one (won't parse) it throws an exception. You would want to provide additional checks to see if it's within the legal timeframe.

                Cheers,

                PS.
                • 5. Re: date validation
                  807607
                  There is a catch with this by the way. If for example you were using the pattern "dd-MMM-yyyy" and put in "45-JAN-2007" it cheerfully gives you the date back (February 14, 2007) which is where the additional checking for range would be required.

                  PS
                  • 6. Re: date validation
                    796440
                    There is a catch with this by the way. If for example
                    you were using the pattern "dd-MMM-yyyy" and put in
                    "45-JAN-2007" it cheerfully gives you the date back
                    (February 14, 2007) which is where the additional
                    checking for range would be required.

                    PS
                    df.setLenient(false);
                    • 7. Re: date validation
                      807607
                      jverd, you're just darn handy on occasion.

                      Cheers,

                      PS.
                      • 8. Re: date validation
                        796440
                        Aw, shucks, ma'am. (*blush*)
                        • 9. Re: date validation
                          807607
                          Ok now you're just bein' creepy jverd.
                          • 10. Re: date validation
                            796440
                            Ok now you're just bein' creepy jverd.
                            Gotta go with what you're good at, dontcha know.
                            • 11. Re: date validation
                              807607
                              Heh ... Well now we know what jverd is good at. Shoulda guessed.
                              • 12. Re: date validation
                                807607
                                cheers guys i'll try these out.

                                basically the over all project is a student fee entery system.
                                so the user gets a text bok poping up and asking for teh usual info, name, address, course code. all these are checked to be in the correct format etc which i have, but two of the required fields are Date of Birth And Fee Date the format can me DD/MM/YYYY or DDMMYYY. but you need to check if it is a valid date in the sense it is a real date.

                                what I was planning on doing if first checling if the string length is either 8 or 10 this should allow for teh use of / or - as seperators. but then I need to check if the string enteres is an actual date, so if you put in 31/06/2007 an error box pops up telling you its invalid and it enters a loop until the date is valid.
                                • 13. Re: date validation
                                  807607
                                  OK I got sorted thanks for teh info

                                  here's what I cam up with,
                                  import javax.swing.JOptionPane; // import class JOptionPane
                                  import java.util.Date; // our objective is a Date
                                  import java.text.SimpleDateFormat; // for parsing and formatting
                                  import java.text.ParseException; // thrown on invalid date

                                  public class Registration
                                  { // start of class

                                  static String feeDate;


                                            while (!inputOK)

                                            {
                                            feeDate = JOptionPane.showInputDialog( "Please Enter The Date The Fees Where Paid in the format dd/mm/yyyy" );
                                            inputOK = callDate(feeDate);
                                            //System.out.println ("we have returned to the main method from callDate and the value passed back is " + studentDOB);
                                            }

                                  inputOK = false;



                                  static boolean callDate(String chkDate)
                                       {
                                            boolean valid = true;
                                            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

                                            // not lenient, otherwise 02/29/2003 becomes 03/01/2003!
                                  dateFormat.setLenient(false);

                                  String strDate = chkDate;

                                            // see if it's a valid date; if so then show it
                                            try
                                            {
                                            Date inputDate = dateFormat.parse(strDate);
                                            System.out.println("Valid Date " + dateFormat.format(inputDate));
                                            return valid;

                                            }
                                            catch (ParseException pe)
                                            {
                                            System.out.println("Invalid date.");
                                            }

                                            return !valid;

                                  } //end callDate Method

                                  } // end of class



                                  Wroks a treat thanks again for teh links