Vaadin 组合框验证

Vaadin combobox validation

我正在尝试使用 Vaadin 验证组合框的值。我的目标是避免提交表单并将所选对象的 'myIntegerAttribute' 字段设置为空。假设组合框存储 'MyBean' class 个对象。

我正在使用 "FilterableListContainer" 绑定数据。 我试过了,但似乎没有触发验证器:

List<MyBean> myBeans = getMyBeansList();
FilterableListContainer filteredMyBeansContainer = new FilterableListContainer<MyBean>(myBeans);
comboBox.setContainerDataSource(filteredMyBeansContainer);
comboBox.setItemCaptionPropertyId("caption");
...
comboBox.addValidator(getMyBeanValidator("myIntegerAttribute"));
...
private BeanValidator getMyBeanValidator(String id){
    BeanValidator validator = new BeanValidator(MyBean.class, id);//TrafoEntity
    return validator;
}

class MyBean {
    String caption;
    Integer myIntegerAttribute;
    ...
}

我不想避免在组合框中选择空值。

如何避免提交空值?

在 Vaadin 7 中,当用户的选择为空时,您将使用 NullValidator 使验证失败:

    NullValidator nv = new NullValidator("Cannot be null", false);
    comboBox.addValidator(nv);

要在对应于用户选择的对象成员为 null 时验证失败,请使用 BeanValidator 在 bean 上包含 @NotNull JSR-303 注释 class:

public class MyBean {

    String caption;

    @NotNull
    int myIntegerAttribute;

    // etc...
}

您使用的是 Viritin 的 FilterableListContainer 吗?我不确定为什么这会阻止验证器被使用,但你能解释一下为什么你将它与组合框一起使用吗?

我以错误的方式实现了验证器。我创建了一个 class 实现 Vaadin 的 'Validator' class:

public class MyBeanValidator implements Validator {
    @Override
    public void validate(Object value) throws InvalidValueException {
        if (!isValid(value)) {
            throw new InvalidValueException("Invalid field");
        }
    }
    private boolean isValid(Object value) {
        if (value == null || !(value instanceof MyBean)
                || ((MyBean) value).getMyIntegerAttribute() == null ) {
            return false;
        }
        return true;
    }
}

并在组合框中使用它:

combobox.addValidator(new MyBeanValidator());

感谢您的回答!