我正在尝试验证文本字段的输入,以便它仅包含 a-z 中的字符。我使用以下方法来验证输入是否为 int:
//VALIDATE IF INPUT IS NUMERIC.
public static boolean isInt(JFXTextField txtUserInput, String userInput) {
try {
int intValidation = Integer.parseInt(userInput);
txtUserInput.setStyle("-fx-border-color: ; -fx-border-width: 0px ;");
return true;
} catch(NumberFormatException exception) {
showErrorMsg("Invalid Input:", "Please enter a numeric-only value");
txtUserInput.setStyle("-fx-border-color: RED; -fx-border-width: 1px ;");
return false;
}
}
如何使用字符串实现此目的?我知道有一种不同的方法可以使用 if 语句来执行此操作,但我想知道是否可以像上面的示例一样捕获异常。
谢谢
最佳答案
使用正则表达式:
if (!userInput.matches("[a-z]+"))
// Has characters other than a-z
如果您也想允许大写:
if (!userInput.matches("[a-zA-Z]+"))
// Has characters other than a-z or A-Z
关于java - 验证输入 - 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086987/