Search code examples
javastringdatejoptionpane

check if a string inserted by user input corresponds to a particular format


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 ?


Solution

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