JavaFX 输入验证文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30935279/
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
JavaFX Input Validation Textfield
提问by BRsmover
I'm using JavaFX and Scene Builder and I have a form with textfields. Three of these textfields are parsed from strings to doubles.
我正在使用 JavaFX 和 Scene Builder,并且我有一个带有文本字段的表单。其中三个文本字段从字符串解析为双精度。
I want them to be school marks so they should only be allowed to be between 1.0 and 6.0. The user should not be allowed to write something like "2.34.4" but something like "5.5" or "2.9" would be ok.
我希望它们是学校分数,所以它们应该只允许在 1.0 和 6.0 之间。用户不应该被允许写类似“2.34.4”的东西,但像“5.5”或“2.9”这样的东西就可以了。
Validation for the parsed fields:
对解析字段的验证:
public void validate(KeyEvent event) {
String content = event.getCharacter();
if ("123456.".contains(content)) {
// No numbers smaller than 1.0 or bigger than 6.0 - How?
} else {
event.consume();
}
}
How can I test if the user inputs a correct value?
如何测试用户输入的值是否正确?
I already searched on Stackoverflow and on Google but I didn't find a satisfying solution.
我已经在 Stackoverflow 和 Google 上搜索过,但没有找到令人满意的解决方案。
采纳答案by griFlo
textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) { //when focus lost
if(!textField.getText().matches("[1-5]\.[0-9]|6\.0")){
//when it not matches the pattern (1.0 - 6.0)
//set the textField empty
textField.setText("");
}
}
});
you could also change the pattern to [1-5](\.[0-9]){0,1}|6(.0){0,1}
then 1,2,3,4,5,6
would also be ok (not only 1.0,2.0,...
)
您也可以将模式更改为[1-5](\.[0-9]){0,1}|6(.0){0,1}
then1,2,3,4,5,6
也可以(不仅1.0,2.0,...
)
updateHere is a small test application with the values 1(.00) to 6(.00) allowed:
更新这是一个允许值 1(.00) 到 6(.00) 的小型测试应用程序:
public class JavaFxSample extends Application {
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Enter number and hit the button");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
Label label1To6 = new Label("1.0-6.0:");
grid.add(label1To6, 0, 1);
TextField textField1To6 = new TextField();
textField1To6.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) { // when focus lost
if (!textField1To6.getText().matches("[1-5](\.[0-9]{1,2}){0,1}|6(\.0{1,2}){0,1}")) {
// when it not matches the pattern (1.0 - 6.0)
// set the textField empty
textField1To6.setText("");
}
}
});
grid.add(textField1To6, 1, 1);
grid.add(new Button("Hit me!"), 2, 1);
Scene scene = new Scene(grid, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
回答by Gianluca Ricciardelli
I would not advise you to use KeyEvent for that.
我不建议您为此使用 KeyEvent。
You should use a more classical way such as validated the user input when the user finish to fill the text field or click on a save button.
您应该使用更经典的方法,例如在用户完成填充文本字段或单击保存按钮时验证用户输入。
/**
* Called this when the user clicks on the save button or finish to fill the text field.
*/
private void handleSave() {
// If the inputs are valid we save the data
if(isInputValid()){
note=(DOUBLE.parseDouble(textField.getText()));
}else // do something such as notify the user and empty the field
}
/**
* Validates the user input in the text fields.
*
* @return true if the input is valid
*/
private boolean isInputValid() {
Boolean b= false;
if (!(textField.getText() == null || textFiled.getText().length() == 0)) {
try {
// Do all the validation you need here such as
Double d = Double.parseInt(textFiled.getText());
if ( 1.0<d<6.0){
b=true;
}
} catch (NumberFormatException e) {
}
return b;
}
回答by Muath Amer
In case you can use a third party library:
如果您可以使用第三方库:
Similar question has been aswered here: Form validator message .
这里已经回答了类似的问题:表单验证器消息 。
For your case, you would choose a RegexValidator
to check the textfield input, and pass the regex that you arrived to from previous answers:
对于您的情况,您可以选择 aRegexValidator
来检查文本字段输入,并传递您从之前的答案中获得的正则表达式:
JFXTextField validationField = new JFXTextField();
validationField.setPromptText("decimal between 1.0 and 6.0");
RegexValidator validator = new RegexValidator();
validator.setRegexPattern("[1-5](\.[0-9]{1,2}){0,1}|6(\.0{1,2}){0,1}");
validator.setMessage("Please enter proper value");
validationField.getValidators().add(validator);
validationField.focusedProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue)
validationField.validate();
});