Validator
interface and has to be implemented by yourself. To simplify things some simple validators are
already implemented. A Validator
has to return true
for valid input and false
for
invalid values.
Validator
is a functional interface which returns true on validation success only.
public interface Validator<T extends Node>{
boolean isValid(T n);
}
Validator
is called depends on the Validation.Type
. Three different types are supported.
Validator#revalidate()
For the ease of use some installation methods are predefined in the Validation
class.
Validation
class provides the Validation.Type
and some convenient installation methods. Generally
adding validation to a node is an easy task and can be done in a single line - see example below.
TextField loginNameField = createTextField();
Validation.installValidator(loginNameField, Validator.createEmptyValidator(loginNameField), Validation.Type.LAZY, Decorator.createWarningDecorator("Field can not be empty!"));
//custom validator - minimum name length is 6
//Validation.installValidator(loginNameField, n -> {return n.getText().length() > 5;}, Validation.Type.LAZY, Decorator.createWarningDecorator("Minimum length is 6!"));
Node
can be used as decorator.
The Decorator
class is a wrapper for the decorator node and allows you to specify some additional parameter where the decorator will appear in relation to
the owner. The static method #createWarningDecorator(String)
creates a warning icon with the specified text as tooltip. Instead or together with a decorator
a style class name for the owner can be specified. The class name will be set as soon as the owner becomes invalid and has to be defined in your CSS file. Additionally the
pseudo class :invalid
is set on the owner node and allows you to define CSS highlighting for specific controls. In the screenshot below the red text color
and the red borders are provided this way. The related CSS is part of the SyntheticaFXModena theme.
Validity
object which represents the validation state of a control since the last validation check. Because
Validity
is a ObjectProperty<Boolean>
, it can be simply bound to other properties. To generate bindings in a fluent style some
convenience methods are already predefined. By default the property is initialized with null
which also means that the related Validator
hasn't been
called so far. A Validity
object can be updated any time by calling Validity#revalidate()
.
TextField loginNameField = createTextField();
Validity v1 = Validation.installValidator(loginNameField, ...);
TextField emailField = createTextField();
Validity v2 = Validation.installValidator(emailField, ...);
Button button = new Button("Create Account");
//button.disableProperty().bind(v1.and(v2).not());
button.setOnAction(e -> {
boolean allValid = v1.and(v2).get();
System.out.println(allValid);
});