【问题标题】:Textfield Validation for no numbers or special characters没有数字或特殊字符的文本字段验证
【发布时间】:2018-03-12 15:51:29
【问题描述】:

我想对不接受特殊字符或数字的文本字段进行验证

public void handle(ActionEvent event) {
            if(fnamefield.getText().matches("[0-9]") || fnamefield.getText().isEmpty()) {
                ErrorAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error!", "Please enter your full name.\n"
                        + "Please make sure no");
                return;
            }

在这里,我尝试仅包含无数字验证,但我不确定如何继续。

【问题讨论】:

  • 应该是.matches(".*[0-9].*")。此外,什么是“特殊字符”?允许使用变音符号吗?美分/抑扬符等呢?
  • 我在想这样的事情:[!@#$%^&*(),.?":{}|]

标签: validation javafx textfield


【解决方案1】:

我认为对您来说一个有效的解决方案是同时检查所有条件。在这种情况下,您正在检查它是否不是空字符串以及它是否仅包含字母和空格。一个有效的正则表达式将是[aA-zZ ]+$。请注意,此正则表达式接受仅包含空格的 String,这可能对您的应用程序有害,但您的方法也会这样做。

显示了如何使用正则表达式匹配所需字符串的示例:

public class MyClass {
    public static void main(String args[]) {
        System.out.println("Are these valid strings?");
        System.out.println("Not valid 1".matches("[aA-zZ ']+$")); //false
        System.out.println("Not valid!".matches("[aA-zZ ']+$")); //false
        System.out.println("".matches("[aA-zZ ']+$")); //false Also invalid
        System.out.println(" ".matches("[aA-zZ ']+$")); //true VALID!!
        System.out.println("For sure I'm valid".matches("[aA-zZ ']+$")); //true
    }
}

在代码示例中,我已将 ' 添加到正则表达式以匹配“I'm”,但如果您不想要它,可以将其删除。

最后,您的代码如下所示:

public void handle(ActionEvent event) {
            if(!fnamefield.getText().matches("[aA-zZ ]+$")) {
                ErrorAlert(Alert.AlertType.ERROR, gridPane.getScene().getWindow(), "Error!", "Please enter your full name.\n"
                        + "Please make sure no");
                return;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-05-16
    • 2011-09-06
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    相关资源
    最近更新 更多