如何在 Vaadin 中使用 StatusChangeListener 进行验证?
How to use StatusChangeListener for validation in Vaadin?
我正在使用活页夹来绑定和验证 TextField
和 ComboBox
。为了获得验证更改的通知,我向活页夹添加了一个 StatusChangeListener。侦听器检查 .hasValidationErrors()
returns 是否为假。但是,在组合框中选择了一个有效条目后,但在文本字段中选择了一个无效条目后 returns false。所以它 returns 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
。
您只是在检查最近更改的组件的值是否有效。如果要检查绑定组件是否存在任何验证错误,请使用 binder.isValid()
.
binder.addStatusChangeListener(status -> System.err.println(binder.isValid()));
请注意,您的布尔值现在已反转。
您可以在官方文档中找到很多有用的示例:
将数据绑定到表单
我正在使用活页夹来绑定和验证 TextField
和 ComboBox
。为了获得验证更改的通知,我向活页夹添加了一个 StatusChangeListener。侦听器检查 .hasValidationErrors()
returns 是否为假。但是,在组合框中选择了一个有效条目后,但在文本字段中选择了一个无效条目后 returns false。所以它 returns 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
。
您只是在检查最近更改的组件的值是否有效。如果要检查绑定组件是否存在任何验证错误,请使用 binder.isValid()
.
binder.addStatusChangeListener(status -> System.err.println(binder.isValid()));
请注意,您的布尔值现在已反转。
您可以在官方文档中找到很多有用的示例: 将数据绑定到表单