仅在使用ValidationSupport

时间:2017-01-12 00:38:08

标签: java forms validation javafx controlsfx

我正在尝试使用ValidationSupport验证javafx表单,验证工作正常,但是当我访问表单时,“错误装饰”已经显示,甚至在表单提交或文本字段集中之前。

ValidationSupport validationSupport = new ValidationSupport();
    validationSupport.registerValidator(textField, Validator.createEmptyValidator("Text is required"));

下图显示了处于初始状态的表单示例。

My Form

如何在用户提交表单或更改TextField值后强制显示装饰?

1 个答案:

答案 0 :(得分:6)

要按需控制控件是CONTROLFx的问题跟踪器上的一个问题(on-demand validation option),它仍处于打开状态,因此ControlsFx尚不支持它。

但是有一种方法可以抑制错误装饰:

ValidationSupport validationSupport = new ValidationSupport();
validationSupport.setErrorDecorationEnabled(false);

稍后,当您确实想要验证时(例如,在提交按钮上),您需要将其重置为默认值:

validationSupport.setErrorDecorationEnabled(true);
validationSupport.redecorate();

这样,每个更改都会对字段进行验证,但在您真正希望显示错误之前,不会显示错误装饰。

实施例

在此示例中,我们只希望在数字字段具有焦点时才能看到验证错误。

public class Sandbox extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane pane = new GridPane();
        pane.add(new Label("Number field:"), 0 , 0);
        TextField numberField = new TextField("");
        pane.add(numberField, 1, 0);
        TextField textField = new TextField("");
        pane.add(new Label("Text field:"), 0, 1);
        pane.add(textField, 1, 1);

        ValidationSupport vs = new ValidationSupport();
        vs.setErrorDecorationEnabled(false); // we don't want errors to bother us for now.
        vs.registerValidator(numberField, Validator.createRegexValidator("must be digits only!", "\\d*", Severity.ERROR));

        // validate and show errors only if number field has the focus
        vs.errorDecorationEnabledProperty().bind(numberField.focusedProperty());

        primaryStage.setScene(new Scene(pane));
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(Sandbox.class);
    }
}

或者如果您想在第一次点击提交按钮后才能看到验证错误:

        ...
        Button button = new Button("Submit");
        pane.add(button, 0, 2);

        ValidationSupport vs = new ValidationSupport();
        vs.setErrorDecorationEnabled(false); // we don't want errors to bother us for now.
        vs.registerValidator(numberField, Validator.createRegexValidator("must be digits only!", "\\d*", Severity.ERROR));


        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                vs.setErrorDecorationEnabled(true); // validate and show errors now!
            }
        });
        ...
相关问题