How to validate fields in vaadin made form

前端 未结 3 1929
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 12:01

I am making a Java project with vaadin. Right now I have a user registration form looking like that:

public class RegistrationComponent extends CustomComponent i         


        
3条回答
  •  天涯浪人
    2021-01-21 12:41

    Vaadin 8

    Using Vaadin 8 com.vaadin.data.Binder easily you can validate your fields. See Binding Data to Forms in the manual.

    Create a TextField and a binder to validate the text field.

    public class MyPage extends VerticalLayout{
         TextField investorCode = new TextField();
         Binder beanBinder = new Binder();
         //Info : MyBean class contains getter and setter to store values of textField.
    
         public MyPage (){
             investorCode.addValueChangeListener(e->valueChange(e));
             addComponent(investorCode);
             bindToBean();
         }
    
         private void bindToBean() {
             beanBinder.forField(investorCode)
             .asRequired("Field cannot be empty")
             .withValidator(investorCode -> investorCode.length() > 0,"Code shold be atleast 1 character long").bind(MyBean::getInvestorCode,MyBean::setInvestorCode);
         }
    
         //rest of the code .....
         private void valueChange(ValueChangeEvent e) {
             beanBinder.validate();
         }
    }
    

    Call validate() from binder will invoke the validation action.

    beanBinder.validate(); 
    

    to validate the filed. You can call this from anywhere in the page. I used to call this on value change or on a button click.

提交回复
热议问题