我在窗口中有字段,其中一些带有验证器,并且全部绑定到属性。 验证按预期进行。
但是-
当任何字段无效时我不想继续。确定验证是否出错的最佳方法是什么?
如果您使用 FieldGroup 实例将字段与属性绑定(这是推荐的方式),您可以编写:
fieldGroup.isValid();
检查由字段组管理的字段的所有字段验证。
Vaadin 中有多种处理验证的方法,Vaadin 均支持这些方法(不需要自定义布尔值 afterValidationFlag)。 这里显示了一种可能的方式(我更喜欢):
public class CustomWindow extends Window {
DateField customBeanFirstPropertyName = new DateField("Caption1");
ComboBox customBeanSecondPropertyName = new ComboBox("Caption2");
TextArea customBeanThirdPropertyName = new TextArea("Caption3");
BeanFieldGroup<CustomBean> binder = new BeanFieldGroup<>(CustomBean.class);
public CustomWindow(CustomBean customBean) {
buildLayout();
binder.buildAndBindMemberFields(this);
binder.setItemDataSource(new BeanItem<>(customBean));
//add validators
customBeanFirstPropertyName.addValidator((Validator) value -> {
if (value == null) throw new Validator.InvalidValueException("nonnull required");
});
customBeanThirdPropertyName.addValidator(
new RegexpValidator(".{3,20}", "length between 3-20 required")
);
/*
or have basic validators on @Entity level with e.g. javax.validation.constraints.Size
example:
@Size(min = 3, max = 20)
@Column(name = "customBeanThirdPropertyName", unique = true)
private String customBeanThirdPropertyName;
*/
}
void commit(Button.ClickEvent event) { //method called by "save" button
try {
binder.commit(); //internally calls valid() method on each field, which could throw exception
CustomBean customBeanAfterValidation = binder.getItemDataSource().getBean(); //custom actions with validated bean from binder
this.close();
} catch (FieldGroup.CommitException e) {
Map<Field<?>, Validator.InvalidValueException> invalidFields = e.getInvalidFields(); //do sth with invalid fields
}
}
}
保持旗帜。在继续之前,请检查该标志是否已设置。在验证代码中,如果验证失败则设置标志。