我正在尝试使用ValidationSupport验证javafx表单,验证工作正常,但是当我访问表单时,"错误装饰"已经显示,甚至在表单提交或文本字段集中之前.
ValidationSupport validationSupport = new ValidationSupport(); validationSupport.registerValidator(textField, Validator.createEmptyValidator("Text is required"));
下图显示了处于初始状态的表单示例.
如何在用户提交表单或更改TextField值后强制显示装饰?
要按需控制控件是ControlsFx的问题跟踪器上的一个问题(按需验证选项),它仍处于打开状态,因此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() { @Override public void handle(ActionEvent event) { vs.setErrorDecorationEnabled(true); // validate and show errors now! } }); ...