Validating and Converting User Input

Binder supports:

  • Validating user input, and

  • Converting value types from types used in business objects to types used in bound UI components, and vice versa.

These concepts go hand in hand, because validation can be based on a converted value, and the ability to convert a value is a kind of validation in itself.

Vaadin includes several validators and converters that you can implement.

Validating User Input

It is typical for applications to restrict the kind of value the user is allowed to enter into certain fields.

Defining Validators

Binder allows you to define validators for each bound field. By default, validators run whenever the user changes the field value. The validation status is also checked when writing to the bean.

You should define the field validator between the forField and bind code lines when creating the binding.

Example: Defining a validator using a Validator instance or an inline lambda expression.

Java

  1. binder.forField(emailField)
  2. // Explicit validator instance
  3. .withValidator(new EmailValidator(
  4. "This doesn't look like a valid email address"))
  5. .bind(Person::getEmail, Person::setEmail);
  6. binder.forField(nameField)
  7. // Validator defined based on a lambda
  8. // and an error message
  9. .withValidator(
  10. name -> name.length() >= 3,
  11. "Name must contain at least three characters")
  12. .bind(Person::getName, Person::setName);
  13. binder.forField(titleField)
  14. // Shorthand for requiring the field to be non-empty
  15. .asRequired("Every employee must have a title")
  16. .bind(Person::getTitle, Person::setTitle);
  • Binder.forField works like a builder: the forField call starts the process, it is followed by various configuration calls for the field, and bind is the final method of the configuration.

  • asRequired is used for mandatory fields:

    • A visual “required” indicator displays.

    • If the user leaves the field empty, an error message displays.

Customizing Validation Error Messages

You can customize the way error messages display by defining a ValidationStatusHandler or configuring the Label for each binding. The label is used to show the status of the field. The label can be used for validation errors, as well as confirmation and helper messages.

Example: Configuring validation messages for email and minimum length validation.

Java

  1. Label emailStatus = new Label();
  2. emailStatus.getStyle().set("color", "Red");
  3. binder.forField(emailField)
  4. .withValidator(new EmailValidator(
  5. "This doesn't look like a valid email address"))
  6. // Shorthand that updates the label based on the
  7. // status
  8. .withStatusLabel(emailStatus)
  9. .bind(Person::getEmail, Person::setEmail);
  10. Label nameStatus = new Label();
  11. binder.forField(nameField)
  12. // Define the validator
  13. .withValidator(
  14. name -> name.length() >= 3,
  15. "Name must contain at least three characters")
  16. // Define how the validation status is displayed
  17. .withValidationStatusHandler(status -> {
  18. nameStatus.setText(status
  19. .getMessage().orElse(""));
  20. nameStatus.setVisible(status.isError());
  21. })
  22. // Finalize the binding
  23. .bind(Person::getName, Person::setName);
  • The withStatusLabel(Label label) method sets the given label to show an error message if the validation fails.

As an alternative to using labels, you can set a custom validation status handler, using the withValidationStatusHandler method. This allows you to customize how the binder displays error messages and is more flexible than using the status label approach.

Adding Multiple Validators

You can add multiple validators for the same binding.

Example: Defining two validators: first, for the email input, and second, for the expected domain.

Java

  1. binder.forField(emailField)
  2. .withValidator(new EmailValidator(
  3. "This doesn't look like a valid email address"))
  4. .withValidator(
  5. email -> email.endsWith("@acme.com"),
  6. "Only acme.com email addresses are allowed")
  7. .bind(Person::getEmail, Person::setEmail);

Triggering Revalidation

The validation of one field can depend on the value of another field. You can achieve this by saving the binding to a local variable and triggering revalidation when the other field fires a value-change event.

Example: Storing a binding for later revalidation.

Java

  1. Binder<Trip> binder = new Binder<>(Trip.class);
  2. DatePicker departing = new DatePicker();
  3. departing.setLabel("Departing");
  4. DatePicker returning = new DatePicker();
  5. returning.setLabel("Returning");
  6. // Store return date binding so we can
  7. // revalidate it later
  8. Binder.Binding<Trip, LocalDate> returningBinding =
  9. binder
  10. .forField(returning).withValidator(
  11. returnDate -> !returnDate
  12. .isBefore(departing.getValue()),
  13. "Cannot return before departing")
  14. .bind(Trip::getReturnDate, Trip::setReturnDate);
  15. // Revalidate return date when departure date changes
  16. departing.addValueChangeListener(
  17. event -> returningBinding.validate());

Converting User Input

You can bind application data to a UI field component, even if the types do not match.

Examples where this is useful include an application-specific type for a postal code that the user enters in a TextField, or requesting the user enter only integers in a TextField, or selecting enumeration values in a Checkbox field.

Defining Converters

Like validators, each binding can have one or more converters, with an optional error message.

You can define converters using callbacks (typically lambda expressions), method references, or by implementing the Converter interface.

Examples: Defining converters.

Java

  1. TextField yearOfBirthField =
  2. new TextField("Year of birth");
  3. binder.forField(yearOfBirthField)
  4. .withConverter(
  5. new StringToIntegerConverter("Not a number"))
  6. .bind(Person::getYearOfBirth,
  7. Person::setYearOfBirth);
  8. // Checkbox for marital status
  9. Checkbox marriedField = new Checkbox("Married");
  10. binder.forField(marriedField).withConverter(
  11. m -> m ? MaritalStatus.MARRIED : MaritalStatus.SINGLE,
  12. MaritalStatus.MARRIED::equals)
  13. .bind(Person::getMaritalStatus,
  14. Person::setMaritalStatus);

Adding Multiple Converters

You can add multiple converters (and validators) for each binding.

Each validator or converter is used in the order defined in the class. The value is passed along until:

  • A final converted value is stored in the business object, or

  • The first validation error or impossible conversion is encountered.

Example: Validator and converter sequence.

Java

  1. binder.forField(yearOfBirthField)
  2. // Validator will be run with the String value
  3. // of the field
  4. .withValidator(text -> text.length() == 4,
  5. "Doesn't look like a year")
  6. // Converter will only be run for strings
  7. // with 4 characters
  8. .withConverter(new StringToIntegerConverter(
  9. "Must enter a number"))
  10. // Validator will be run with the converted value
  11. .withValidator(year -> year >= 1900 && year < 2000,
  12. "Person must be born in the 20th century")
  13. .bind(Person::getYearOfBirth,
  14. Person::setYearOfBirth);

When updating UI components, values from the business object are passed through each converter in reverse order (without validation).

Note
Although it is possible to use a converter as a validator, best practice is to use a validator to check the contents of a field, and a converter to modify the value. This improves code clarity and avoids excessive boilerplate code.

Conversion Error Messages

You can define a custom error message to be used if a conversion throws an unchecked exception.

When using callbacks, you should provide one converter in each direction. If the callback used for converting the user-provided value throws an unchecked exception, the field is marked as invalid, and the exception message is used as the validation error message. Java runtime exception messages are typically written for developers, and may not be suitable for end users.

Example: Defining a custom conversion error message.

Java

  1. binder.forField(yearOfBirthField)
  2. .withConverter(
  3. Integer::valueOf,
  4. String::valueOf,
  5. // Text to use instead of the
  6. // NumberFormatException message
  7. "Please enter a number")
  8. .bind(Person::getYearOfBirth,
  9. Person::setYearOfBirth);

Implementing the Converter Interface

There are two methods to implement in the Converter interface:

  • convertToModel receives a value that originates from the user.

    • The method returns a Result that either contains a converted value or a conversion error message.
  • convertToPresentation receives a value that originates from the business object.

    • This method returns the converted value directly. It is assumed that the business object only contains valid values.

Example: Implementing a String to Integer Converter.

Java

  1. class MyConverter
  2. implements Converter<String, Integer> {
  3. @Override
  4. public Result<Integer> convertToModel(
  5. String fieldValue, ValueContext context) {
  6. // Produces a converted value or an error
  7. try {
  8. // ok is a static helper method that
  9. // creates a Result
  10. return Result.ok(Integer.valueOf(
  11. fieldValue));
  12. } catch (NumberFormatException e) {
  13. // error is a static helper method
  14. // that creates a Result
  15. return Result.error("Enter a number");
  16. }
  17. }
  18. @Override
  19. public String convertToPresentation(
  20. Integer integer, ValueContext context) {
  21. // Converting to the field type should
  22. // always succeed, so there is no support for
  23. // returning an error Result.
  24. return String.valueOf(integer);
  25. }
  26. }
  27. // Using the converter
  28. binder.forField(yearOfBirthField)
  29. .withConverter(new MyConverter())
  30. .bind(Person::getYearOfBirth, Person::setYearOfBirth);
  • The provided ValueContext can be used to find the Locale to be used for the conversion.