绑定验证电子邮件以禁用按钮属性

时间:2016-10-30 11:59:03

标签: javafx binding

我想禁用按钮CREATE ACCOUNT所有字段都未正确填充。

我配置了强制验证:

    this.buttonRegister.setDisable(true);   
    BooleanBinding disableBinding = this.mailBox.textProperty().isEmpty()
            .or(this.loginField.textProperty().isEmpty()).or(this.passwordField.textProperty().isEmpty())
            .or(this.passwordConfirmField.textProperty().isEmpty())
            .or(this.passwordField.textProperty().isNotEqualTo(this.passwordConfirmField.textProperty()));

    this.buttonRegister.disableProperty().bind(disableBinding);

我还想添加电子邮件验证。我有一个功能。但我不能添加这个。我的disableBinding。

private Boolean emalValidation() {
    Pattern p = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");
    Matcher m = p.matcher(this.mailBox.getText());              
    if(m.find() && m.group().equals(this.mailBox.getText())) {
        return Boolean.TRUE ;
    } else {
        return Boolean.FALSE;
    }
}

如何为此验证构造布尔属性?

1 个答案:

答案 0 :(得分:0)

您可以多次使用or方法创建disableBinding,也可以使用Bindings.createBooleanBinding进行自定义Callable<Boolean>检查,无论输入是否有效并添加结果所依赖的所有属性作为依赖项:

final Pattern pattern = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9._]*@[a-zA-Z0-9]+([.][a-zA-Z]+)+");

BooleanBinding disableBinding = Bindings.createBooleanBinding(() -> 
        this.loginField.getText().isEmpty()
         || this.passwordField.getText().isEmpty()
         || !this.passwordConfirmField.getText().equals(passwordField.getText())
         || !pattern.matcher(this.mailBox.getText()).matches(),
    this.mailBox.textProperty(),
    this.loginField.textProperty(),
    this.passwordField.textProperty(),
    this.passwordConfirmField.textProperty());

请注意,我删除了2个条件,因为如果其中一个为空且模式与空字符串不匹配,则2个相等的字符串为空。

请注意,您当然只能为BooleanBinding检查创建emalValidation(),但我不建议:

...
.or(Bindings.createBooleanBinding(this::emalValidation,
                                  this.mailBox.textProperty()).not());