ControlsFX复杂验证

时间:2015-10-28 14:03:15

标签: validation javafx controlsfx

我需要使用密码和密码确认验证简单的JavaFX表单。

validationSupport.registerValidator(passwordInput,
                  Validator.createEmptyValidator("Password required!"));
validationSupport.registerValidator(confirmPasswordInput,
                  new EqualsToValidator(passwordInput.textProperty(),
                                  "Password differs from confirmation"));

在EqualsToValidator中,我只是比较传递给验证者的property.getValue()value

如果我更改 密码EqualsToValidator ,则因为它正在收听confirmPasswordInput而不是passwordInput

我只找到了丑陋的解决方案:

passwordInput.textProperty().addListener((observable, oldValue, newValue) -> {
    String oldText = confirmPasswordInput.getText();
    confirmPasswordInput.setText(null);
    confirmPasswordInput.setText(oldText);
});

当另一个字段发生变化时如何使一个字段无效?

2 个答案:

答案 0 :(得分:1)

My implementation

Validator.java - 验证器的基类。

TextValidator.java和PasswordValidator.java - 实现。

ValidationSupport.java跟踪所有验证器。

用法:

validationSupport.addValidator(new TextValidator(usernameInput, "Username is required!"));
validationSupport.addValidator(new TextValidator(passwordInput, "Password is required!"));
validationSupport.addValidator(new PasswordValidator(passwordInput, confirmPasswordInput, "Password differs from confirmation"));

答案 1 :(得分:-1)

这对我有用。我只是复制了ValidationSupport类并添加了以下代码。

@SuppressWarnings("unchecked")
public <T> void reaplyValidator(Control target){

    if(!controls.containsKey(target)){
        throw new NullPointerException("The given control was not registered");
    }

    ValueExtractor.getObservableValueExtractor(target).map( e -> {

        ObservableValue<T> observable = (ObservableValue<T>) e.call(target);
        Validator<T> validator = (Validator<T>) controls.get(target);

        Platform.runLater(() -> validationResults.put(target, validator.apply(target, observable.getValue())));

        dataChanged.set(true);

        return e;

    });
}

public void revalidate(){
    for(Control c : getRegisteredControls()){
        reaplyValidator(c);
    }
}

您还需要更改控件设置为Map以保留验证器。

private ObservableMap<Control, Validator<?>> controls = FXCollections.observableMap(new HashMap<>());