0

i have this method that ask the user for an input(a Date) in a specific format -- DD/MM/YYYY and i managed to partially limit the user input by this way using this code

date.matches("[0-9]+[0-9]/[0-9]+[0-9]/[0-9]+[0-9]+[0-9]+[0-9]"));

but i still got a problem on the input because if the user insert a date like 12121/12121212/12121 it takes it like a good input and goes forward

the input cicle is determined by this portion of code using a JOptionPane

String date  = JOptionPane.showInputDialog(frame,"Inserisci la data di partenza separata da / (GG/MM/AAAA):");
    if (date ==null) { return;}
    while (!date.matches("[0-9]+[0-9]/[0-9]+[0-9]/[0-9]+[0-9]+[0-9]+[0-9]")) {          
        JOptionPane.showMessageDialog(frame, "Data inserita errata");
        date  = JOptionPane.showInputDialog(frame,"Inserisci la data di partenza separata da / (GG/MM/AAAA):"); }

then i split the string by using

String[] parts = date.split("/");
    int year = Integer.parseInt(parts[2]);
    int month = Integer.parseInt(parts[1]);
    int day = Integer.parseInt(parts[0]);

how can i get this to work limiting the numbers of digits of the inserted string ?

The BigBoss
  • 111
  • 2
  • 11
  • Remove all the `'+'` in your regular expression. – Flavio Jan 31 '14 at 16:17
  • You could try to parse the String with SimpleDateFormat, catch the exception and return false. This could probably be the dirtiest but the easiest way to do it – jsedano Jan 31 '14 at 16:17
  • Notice you can still enter stuff like 54/23/2014, so this is far from perfect! As other said, you should probably use a date parser. – Flavio Jan 31 '14 at 16:39

1 Answers1

1

You should try to parse it as a date of the given format and catch parse errors. Take a look at SimpleDateFormat

khachik
  • 28,112
  • 9
  • 59
  • 94