2017-04-06 64 views
0

我想驗證與Vaadin組合框的值。我的目標是避免將所選對象的'myIntegerAttribute'字段設置爲null來提交表單。假設組合框存儲「MyBean」類對象。Vaadin combobox驗證

我正在使用「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; 
    ... 
} 

我不希望避免在下拉列表中選擇空值。

如何避免提交空值?

+0

您是否在表單中使用活頁夾或手動向組件添加布局?顯示包含「提交」部分的完整代碼將有助於理解您的方案。 – Morfic

+0

是的,我在主帖中增加了更多細節。 – Ortzi

回答

0

我以錯誤的方式實施驗證器。我創建了一個類實現Vaadin的「驗證」類:

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

感謝您的答案!

+0

如果你不想使用BeanValidator,那肯定是一種方法。 –

1

在Vaadin 7,你可以使用NullValidator當用戶的選擇是空驗證失敗:

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?我不知道爲什麼這會阻止驗證器被使用,但是你能解釋爲什麼你要使用組合框嗎?

+0

這不行,因爲combobox值永遠不爲null,null值可能是'MyClass'類型對象的'myIntegerAttribute'屬性。我使用FilterableListContainer將'myBean'值綁定到我的表單的字段(顯然,除了組合框以外,我還有更多的字段)。我認爲這個問題與你說的相關 – Ortzi

+0

@Ortzi:答案已經更新,包括如何處理空bean成員。 –