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

    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.

    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);

    Java

    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. DatePicker departing = new DatePicker();
    2. departing.setLabel("Departing");
    3. DatePicker returning = new DatePicker();
    4. returning.setLabel("Returning");
    5. // Store return date binding so we can revalidate it later
    6. Binder.BindingBuilder<Trip, LocalDate> returnBindingBuilder = binder
    7. .forField(returning).withValidator(
    8. returnDate -> !returnDate
    9. .isBefore(departing.getValue()),
    10. "Cannot return before departing");
    11. Binder.Binding<Trip, LocalDate> returnBinder = returnBindingBuilder
    12. .bind(Trip::getReturnDate, Trip::setReturnDate);
    13. // Revalidate return date when departure date changes
    14. 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

    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.

    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. .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 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

    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())

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