Skip to content
javahacks.dev
Vaadin

How to Build Forms With Binder and Validation in Vaadin

Bind form fields to a bean with Vaadin's Binder, add required checks and custom validators, show errors per field and save only when the data is valid.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the Vaadin, CSS, HTML5 and Thymeleaf logos.

A form is a set of fields, a bean they edit, a list of rules, and a save button. Vaadin's Binder is the piece that connects them: it copies values from the bean into the fields, validates as the user types, shows each error beside the field it belongs to, and copies valid values back. This post builds a customer form with it, then covers the cases that cause the most confusion. The project setup is in the Vaadin tutorial, and the design view is in building web UIs in pure Java with Vaadin.

A bean and a form

Customer.javajava
public class Customer {
    private String name;
    private String email;
    private Integer age;
    // getters and setters
}
CustomerForm.javajava
public class CustomerForm extends FormLayout {

    private final TextField name = new TextField("Name");
    private final EmailField email = new EmailField("Email");
    private final IntegerField age = new IntegerField("Age");
    private final Button save = new Button("Save");
    private final Binder<Customer> binder = new Binder<>(Customer.class);

    public CustomerForm(Consumer<Customer> onSave) {
        binder.forField(name)
              .asRequired("Name is required")
              .bind(Customer::getName, Customer::setName);

        binder.forField(email)
              .asRequired("Email is required")
              .withValidator(new EmailValidator("Enter a valid email address"))
              .bind(Customer::getEmail, Customer::setEmail);

        binder.forField(age)
              .withValidator(a -> a == null || a >= 18, "Customers must be 18 or older")
              .bind(Customer::getAge, Customer::setAge);

        save.addClickListener(e -> {
            Customer customer = new Customer();
            if (binder.writeBeanIfValid(customer)) {
                onSave.accept(customer);
            }
        });

        add(name, email, age, save);
    }

    public void edit(Customer customer) {
        binder.readBean(customer);
    }
}

IntegerField supplies an Integer directly, so there is nothing to convert. When a TextField is bound to a number, add withConverter(new StringToIntegerConverter("Enter a whole number")) before bind, and a failed conversion shows the message as a validation error.

What each call does

CallEffect
forField(field)Starts a binding for one field
asRequired(message)Marks the field required and shows the message when it is empty
withValidator(...)Adds a rule that returns a message when it fails
bind(getter, setter)Completes the binding for one property
readBean(bean)Fills the fields from the bean and clears any errors
writeBeanIfValid(bean)Writes values to the bean only when every validator passes

The field shows its error as the user leaves it. On save, writeBeanIfValid validates the whole form at once and marks every invalid field, so a user who clicks Save on an empty form sees all the problems together, not one at a time.

Reuse the Bean Validation annotations

If the bean already carries Jakarta Bean Validation annotations because the same class serves a REST API, do not write the rules twice:

java
public class Customer {
    @NotBlank private String name;
    @Email @NotBlank private String email;
    @Min(18) private Integer age;
}

var binder = new BeanValidationBinder<>(Customer.class);
binder.bindInstanceFields(this);

bindInstanceFields matches the names of the form's fields to the bean's properties, so a field called name binds to getName. Messages come from the annotation or from the validation message bundle. This needs a Bean Validation implementation on the classpath, which Spring Boot supplies through the validation starter. Keep explicit forField bindings for the fields that need converters or messages different from the annotation's.

Enable Save only when it makes sense

java
binder.addStatusChangeListener(event -> save.setEnabled(binder.isValid() && binder.hasChanges()));

The listener runs whenever validity changes. hasChanges is true once a field differs from the bean it was read from, which keeps Save disabled on an untouched form. Disabling the button is a convenience. The real check is the one on save, and the server must repeat it, because the browser is not trusted.

setBean versus readBean

binder.setBean(customer) binds the bean directly, and every valid change writes through to it at once. That suits a small inline editor, and it is wrong for a dialog with a Cancel button, because the bean has already been changed when the user cancels. With readBean and writeBeanIfValid, the bean changes only on an explicit save, and Cancel has nothing to undo. Calling readBean(null) clears the form for a new entry.

Rules that involve more than one field

java
binder.withValidator(
        c -> c.getAge() == null || c.getEmail() != null,
        "Email is needed when age is given");

A validator added to the binder itself sees the whole bean and runs after the field validators, when the form is written. Its message has no field to appear beside, so attach a label for it with binder.setStatusLabel(label).

Converters, and why a field can fail before any validator runs

A TextField holds a string, and a bean property is often something else: a number, a date, an enum. A converter sits between them, and it can fail. When it does, the failure is reported exactly like a validation error, beside the field, and the bean is not written. That is why a user who types abc into an age field sees "Enter a whole number" and not an exception.

java
binder.forField(ageText)
      .withConverter(new StringToIntegerConverter("Enter a whole number"))
      .withValidator(a -> a >= 18, "Customers must be 18 or older")
      .bind(Customer::getAge, Customer::setAge);

The order matters and it is easy to get backwards. Validators added before the converter see the string, and validators added after it see the converted number. In the snippet above the range check runs on an Integer, which is what you want. If you put withValidator(a -> a >= 18, ...) before withConverter, the lambda would receive a String and the code would not compile, which is the compiler pointing out the mistake for you.

Empty input is the second thing to decide. An empty TextField yields an empty string, and the standard converter treats it as null. With asRequired, null is rejected. Without it, null reaches your validator, which is why the earlier age rule starts with a == null ||. Forgetting that guard produces a NullPointerException inside a validator, and Vaadin reports it as a failed validation with no useful text. A dedicated converter is also the place for a business type: a Converter<String, Sku> that rejects anything that is not three letters and four digits keeps that rule out of every form that edits a SKU.

Showing errors that come from the server

Some rules cannot be checked in the form, such as an email that is already registered. Catch the service's exception when saving and attach the message to the field:

java
try {
    customers.register(customer);
} catch (EmailTaken e) {
    email.setErrorMessage("That address is already registered");
    email.setInvalid(true);
}

The field clears the flag itself the next time its value changes, so there is nothing to reset. This is the case where the browser-side rules and the real rule are different, and the real one wins. Show the message, keep the user's input in place, and do not clear the form.

Resetting the form after a save

After a successful save, call binder.readBean(new Customer()) to show an empty form for the next entry, or binder.readBean(saved) to keep showing the stored record. Do not reuse the old bean instance for the next entry, because the previous values stay in it. Focus the first field again with name.focus(), so a user entering a series of records can keep typing without reaching for the mouse.

The server is the authority

The messages in the browser are a convenience. A client can be bypassed, so enforce the same rules in the service that saves the customer, using the annotations on the bean and a Validator call or a validated method parameter. In Vaadin, the code runs on the server already, which makes this easier than in a single-page application, but a REST endpoint that accepts the same bean needs its own check. The reasoning is in how the server-side model works. A wizard with several steps usually uses one binder per step. The reference pages are the Binder documentation and the validation chapter.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.