如何使用StatusChangeListener进行验证?

问题描述 投票:1回答:1

我正在使用绑定器来绑定和验证TextFieldComboBox。为了获得验证更改的通知,我将StatusChangeListener添加到绑定器。监听器检查.hasValidationErrors()是否返回false。但是,在组合框中选择有效条目后,文本字段中的条目无效,则返回false。因此,即使存在验证错误,它也会返回false。请参阅下面的最小示例。

public class TestWindow extends Window {

    private final Binder<State> binder;

    public TestWindow() {
        this.binder  = new Binder<>();

        ComboBox<String> comboBox = new ComboBox<>("comboBox", List.of("A", "B"));
        TextField textField = new TextField("textField");

        this.binder.forField(comboBox).bind(State::getComboBox, State::setComboBox);
        this.binder.forField(textField)
                .withValidator(string -> string.length() > 3, "tmp")
                .bind(State::getName, State::setName);
        this.binder.addStatusChangeListener( status -> System.err.println(status.hasValidationErrors()));

        setContent(new VerticalLayout(comboBox, textField));
    }


    private class State {
        private String name;
        private String comboBox;

        public State(String name, String comboBox) {
            this.name = name;
            this.comboBox = comboBox;
        }

        public String getComboBox() {
            return this.comboBox;
        }

        public void setComboBox(String comboBox) {
            this.comboBox = comboBox;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

输入一个在文本字段中太短的字符串并在组合框中选择一些内容后,我希望打印true

java vaadin
1个回答
2
投票

您只是检查最近更改的组件的值是否有效。如果要检查绑定组件是否存在任何验证错误,请使用binder.isValid()

 binder.addStatusChangeListener(status -> System.err.println(binder.isValid()));

请注意,您的布尔值现在已反转。

你可以在官方文档中找到很多有用的例子:qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.