Validation
Overview
Validation checks values against constraints.
There are two ways to use validation features in Helidon SE:
- Have a
@Validation.Validatedannotated type and use aTypeValidatorservice to validate it - Invoke the constraint checks directly using
Validatorsstatic methods
The feature fit with our Helidon Declarative, which is a preview feature.
Maven Coordinates
To enable Validation, add the following dependency to your project’s pom.xml
(see Managing Dependencies).
Usage
Validated type
A type annotated with @Validation.Validated will have validation code
generated.
Example of a validated type:
@Validation.Validated
record MyType(@Validation.String.Pattern(".*valid.*") @Validation.NotNull String validString,
@Validation.Integer.Min(42) int validInt) {
}
Such code can then be validated using a service TypeValidation:
Example of validating a type:
TypeValidation validator = Services.get(TypeValidation.class);
var validationResponse = validator.validate(MyType.class, new MyType("valid", 43));
Or using the check method(s) that throw a ValidationException:
Example of validating a type that throws an exception:
TypeValidation validator = Services.get(TypeValidation.class);
// throws a ValidationException if the object is invalid
validator.check(MyType.class, new MyType("valid", 43));
The following annotation processing setup must be done to generate the code:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.helidon.bundles</groupId>
<artifactId>helidon-bundles-apt</artifactId>
<version>${helidon.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
Validate Object
An object can be validated using one of the built-in constraints through methods on
Example of validating an object using a built-in constraint:
var validationResponse = Validators.validateNotNull(anInstance);
Example of validating an object using a built-in constraint that throws an exception:
// throws a ValidationException if the object is invalid
Validators.checkNotNull(anInstance);
The low-level approach allows use of any constraint (including custom constraints) through programmatic API. Note that an instance of the validator can be cached as long as it is used for the same type and constraint configuration.
The first approach gives as a validation response:
Example of validating an object using any constraint:
And the second throws an exception if validation failed:
Example of validating an object using any constraint that throws an exception: