java 验证输入对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5157482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:44:29  来源:igfitidea点击:

Validate Input Dialog box

javaswingjoptionpane

提问by James

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

我想做的是向用户提供 JOptionPane.showInputDialog(null,... 并检查

  1. it is not blank
  2. it does not contain numbers or special characters like /><.!"£$%^&*()
  1. 它不是空白
  2. 它不包含数字或特殊字符,如 /><.!"£$%^&*()

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!

请怜悯我的愚蠢!提前感谢您的任何帮助,它是 appericiated !

采纳答案by Oskar Lund

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.

!inputValue.matches("[A-Za-z]*")除了任意数量的字母 a 到 z(大写或小写)之外的任何输入时,Where将触发。

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);

回答by jzd

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.

可能想要使用 do while 循环或类似于始终循环一次的东西。您还需要使用正则表达式来验证不存在特殊字符。