Validating and Converting User Input

Binder supports checking the validity of the user’s input and converting the values between the type used in business objects and the bound UI components. These two concepts go hand in hand since validation can be based on a converted value, and being able to convert a value is a kind of validation.

Validation

An application typically has some restrictions on exactly what kinds of values the user is allowed to enter into different fields. Binder lets us define validators for each field that we are binding. The validator is by default run whenever the user changes the value of a field, and the validation status is also checked again when saving.

Validators for a field are defined between the forField and bind steps when a binding is created. A validator can be defined using Validator instance or inline using a 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 and an error message
  8. .withValidator(
  9. name -> name.length() >= 3,
  10. "Full name must contain at least three characters")
  11. .bind(Person::getName, Person::setName);
  12. binder.forField(titleField)
  13. // Shorthand for requiring the field to be non-empty
  14. .asRequired("Every employee must have a title")
  15. .bind(Person::getTitle, Person::setTitle);
Note
Binder.forField works like a builder where forField starts the process, is followed by various configuration calls for the field and bind acts as the finalizing method which applies the configuration.

The validation state of each field is updated whenever the user modifies the value of that field.

To customize the way a binder displays error messages is to configure each binding to use its own Label that is used to show the status for each field.

Note
The status label is not only used for validation errors but also for showing confirmation and helper messages.

Java

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

It is possible to add multiple validators for the same binding. The following example will first validate that the entered text looks like an email address, and only for seemingly valid email addresses it will continue checking that the email address is 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);

In some cases, the validation of one field depends on the value of some other field. We can save the binding to a local variable and trigger a revalidation when another field fires a value change event.

Java

  1. Binder<Trip> binder = new Binder<>();
  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 revalidate it later
  7. Binder.BindingBuilder<Trip, LocalDate> returnBindingBuilder = binder
  8. .forField(returning).withValidator(
  9. returnDate -> !returnDate
  10. .isBefore(departing.getValue()),
  11. "Cannot return before departing");
  12. Binder.Binding<Trip, LocalDate> returnBinder = returnBindingBuilder
  13. .bind(Trip::getReturnDate, Trip::setReturnDate);
  14. // Revalidate return date when departure date changes
  15. departing.addValueChangeListener(event -> returnBinder.validate());

Conversion

You can also bind application data to a UI field component even though the types do not match. In some cases, there might be types specific for the application, such as custom type that encapsulates a postal code that the user enters through a TextField. Another quite typical case is for entering integer numbers using a TextField or enumeration values (Checkbox is used as an example). Similarly to validators, we can define a converter using Converter instance or inline using lambda expressions. We can optionally specify also an error message.

Java

  1. TextField yearOfBirthField = new TextField("Year of birth");
  2. binder.forField(yearOfBirthField)
  3. .withConverter(
  4. new StringToIntegerConverter("Must enter a number"))
  5. .bind(Person::getYearOfBirth, Person::setYearOfBirth);
  6. // Checkbox for gender
  7. Checkbox genderField = new Checkbox("Gender");
  8. binder.forField(genderField)
  9. .withConverter(gender -> gender ? Gender.FEMALE : Gender.MALE,
  10. gender -> Gender.FEMALE.equals(gender))
  11. .bind(Person::getGender, Person::setGender);

Multiple validators and converters can be used for building one binding. Each validator or converter is used in the order they were defined for a value provided by the user. The value is passed along until a final converted value is stored in the business object, or until the first validation error or impossible conversion is encountered. When updating the UI components, values from the business object are passed through each converter in the reverse order without doing any validation.

Note
A converter can be used as a validator but for code clarity and to avoid boilerplate code, you should use a validator when checking the contents and a converter when modifying the value.

Java

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

You can define your own conversion either by using callbacks, typically lambda expressions or method references, or by implementing the Converter interface.

When using callbacks, there is one for converting in each direction. If the callback used for converting the user-provided value throws an unchecked exception, then the field will be marked as invalid and the message of the exception will be used as the validation error message. Messages in Java runtime exceptions are typically written with developers in mind and might not be suitable to show to end users. We can provide a custom error message that is used whenever the conversion throws an unchecked exception.

Java

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

There are two separate methods to implement in the Converter interface. convertToModel receives a value that originates from the user. The method should return a Result that either contains a converted value or a conversion error message. convertToPresentation receives a value that originates from the business object. Since it is assumed that the business object only contains valid values, this method directly returns the converted value.

Java

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

The provided ValueContext can be used for finding Locale to be used for the conversion.