Validate Input Dialog box

James picture James · Mar 1, 2011 · Viewed 11.1k times · Source

HI, I feel rather stupid asking this as I should be able to do it but I can't! I have also checked on the net and in my book and for such a simple thing there is nothing (or I can see it).

What I wanna do is present a user with a JOptionPane.showInputDialog(null,... and check

  1. it is not blank
  2. it does not contain numbers or special characters like /><.!"£$%^&*()

if it fails any of these tests to re-show the box so they have to do it, eurgh this is such a simple thing but I just can't work it out :(

Please have pitty on my stupidity! Thanks for any help in advance it is appericiated!

Answer

Oskar Lund picture Oskar Lund · Mar 2, 2011

Have a method that shows the input dialog, validates the input and returns the input if it's ok, else it calls itself to repeat the process until the input is valid. Something like this:

private String showInputDialog()
{
    String inputValue = JOptionPane.showInputDialog("Please input something");

    if(inputValue == null || inputValue.isEmpty() || !inputValue.matches("[A-Za-z]*"))
    {
        inputValue = showInputDialog();
    }

    return inputValue;
}

Where !inputValue.matches("[A-Za-z]*") will trigger on any input other than any number of letters a to z, upper or lower case.

Then from your code you just call it and the do whatever you want with the return value.

String input = showInputDialog();
System.out.println(input);