Validate Input Dialog box
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 si开发者_JAVA百科mple thing there is nothing (or I can see it).
What I wanna do is present a user with a JOptionPane.showInputDialog(null,... and check
- it is not blank
- 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!
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);
Do just as you describe. Display the dialog and check the result. If it is not valid display the dialog again.
Might want to use a do while loop or something similar to always loop once. Also you will want to use a regular expression to validate that no special characters exist.
精彩评论