Validation Vaadin组合框验证

Validation Vaadin组合框验证,validation,combobox,vaadin,vaadin7,Validation,Combobox,Vaadin,Vaadin7,我试图用Vaadin验证组合框的值。我的目标是避免提交所选对象的“myIntegerAttribute”字段设置为null的表单。假设组合框存储“MyBean”类对象 我正在使用“FilterableListContainer”绑定数据。 我尝试过这个,但似乎验证程序没有被触发: List<MyBean> myBeans = getMyBeansList(); FilterableListContainer filteredMyBeansContainer = new Filtera

我试图用Vaadin验证组合框的值。我的目标是避免提交所选对象的“myIntegerAttribute”字段设置为null的表单。假设组合框存储“MyBean”类对象

我正在使用“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;
    ...
}
List myBeans=getMyBeansList();
FilterableListContainer filteredMyBeansContainer=新的FilterableListContainer(myBeans);
comboBox.setContainerDataSource(filteredMyBeansContainer);
comboBox.setItemCaptionPropertyId(“标题”);
...
addValidator(getMyBeanValidator(“myIntegerAttribute”);
...
私有BeanValidator getMyBeanValidator(字符串id){
BeanValidator validator=新的BeanValidator(MyBean.class,id);//流量实体
返回验证器;
}
类MyBean{
字符串标题;
整型myIntegerAttribute;
...
}
我不想避免在组合框中选择null值


如何避免提交空值?

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

    NullValidator nv = new NullValidator("Cannot be null", false);
    comboBox.addValidator(nv);
若要在与用户选择相对应的对象成员为null时验证失败,请使用BeanValidator在bean类上包含@NotNull JSR-303注释:

public class MyBean {

    String caption;

    @NotNull
    int myIntegerAttribute;

    // etc...
}

您正在使用Viritin的FilterableListContainer吗?我不知道为什么这会阻止验证程序被使用,但是你能解释一下为什么你要将它与组合框一起使用吗?

我以错误的方式实现了验证程序。我创建了一个实现Vaadin的“Validator”类的类:

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());

谢谢你的回答

您是在表单中使用活页夹还是在布局中手动添加组件?显示包含“提交”部分的完整代码将有助于理解您的场景。是的,我在主要帖子中添加了更多详细信息。这不起作用,因为combobox值从不为null,null值可以是“MyClass”类型对象的“myIntegerAttribute”属性。我使用FilterableListContainer将“myBean”值绑定到表单的字段(显然,除了combobox之外,我还有更多字段)。我认为问题与你所说的有关said@Ortzi:答案已更新,包括如何处理空bean成员。如果您不想使用BeanValidator,这肯定是一种方法。