2017-02-17 94 views
0

我有一個窗口中的字段,其中一些帶有驗證器並且都綁定到屬性。 驗證按預期工作。檢查所有字段是否有效的最佳方法是什麼?

但是 -

我不想繼續當任何字段無效。確定驗證是否出錯的最佳方法是什麼?

+0

取決於您使用的數據模型,但這裏有一個有趣的鏈接http://demo.vaadin.com/book-examples-vaadin7/book#component.field.validation.basic –

回答

0

維護一面旗幟。在繼續之前,檢查是否設置了標誌。在驗證代碼中,如果驗證失敗,則設置標誌。

+0

我爲Validator代理創建了一個工廠類它跟蹤所有驗證並能夠返回所有驗證器是否驗證。像這樣工作'textField.addValidator(allValid.too(new EmailValidator(「請輸入一個有效的電子郵件地址」)));''和'allValid.isAllValid()' –

1

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 
     } 
    } 
} 
1

如果使用FIELDGROUP實例綁定的屬性,這是推薦的方式你的領域,你可以這樣寫:

fieldGroup.isValid(); 

這將檢查字段組管理的字段的所有字段驗證。

相關問題