Search code examples
validationcomboboxvaadinvaadin7

Vaadin combobox validation


I'm trying to validate the value of a combobox with Vaadin. My goal is to avoid committing the form with the selected object's 'myIntegerAttribute' field setted to null. Supose that the combobox stores 'MyBean' class objects.

I'm using a "FilterableListContainer" to bind the data. I tried this, but it seems that the validator is not being fired:

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;
    ...
}

I don't want to avoid selecting null value in the combobox.

How can I avoid commiting the null value?


Solution

  • I was implementing the validator in the wrong way. I created a class implementing Vaadin's '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;
        }
    }
    

    And used it in the combobox:

    combobox.addValidator(new MyBeanValidator());
    

    Thank you for the answers!