Home > Software engineering >  Allow empty field and validate if not empty in Vaadin
Allow empty field and validate if not empty in Vaadin

Time:11-15

I have an input field in my form that when it is empty and form is submitted, I want to allow the form to submit. And the field is not empty, I want it to be validated. This is the code I have so far, but the field gets a validation error when I submit the form and field is empty:

  binder.forField(field)
        .withValidator(field-> field.matches(REGEX),
            FORMAT_ERROR_MSG)
        .bind("field");

CodePudding user response:

The straightforward way is to make your validator accept the value if it's empty or if it matches your regular expression.

  binder.forField(field)
        .withValidator(value -> value.isEmpty() || value.matches(REGEX),
            FORMAT_ERROR_MSG)
        .bind("field");
  • Related