Custom Validators in Quarkus
This article provides an overview of validators in the Quarkus Java framework and delves deeply into custom validators with examples
Join the DZone community and get the full member experience.
Join For FreeQuarkus is an open-source, full-stack Java framework designed for building cloud-native, containerized applications. As Quarkus is built for cloud applications, it is designed to be lightweight and fast and supports fast startup times. A well-designed containerized application facilitates the implementation of reliable REST APIs for creating and accessing data.
Data validation is always an afterthought for developers but is important to keep the data consistent and valid. REST APIs need to validate the data it receives, and Quarkus provides rich built-in support for validating REST API request objects. There are situations where we need custom validation of our data objects. This article describes how we can create custom validators using the Quarkus framework.
REST API Example
Let’s consider a simple example below where we have a House data object and a REST API to create a new House.
The following fields need to be validated:
number
: should be not null.street
: should not be blank.state
: should be only California (CA) and Nevada (NV).
class House {
String number;
String street;
String city;
String state;
String type;
}
And the REST API:
@Path("/house")
public class HouseResource {
@POST
public String createHouse(House house) {
// Additional logic to process the house object
return "Valid house created";
}
}
Configure Quarkus Validator
Quarkus provides the Hibernate validator to perform data validation. This is a Quarkus extension and needs to be added to the project.
For Maven projects, add the dependency to the pom.xml
:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
For Gradle-based projects, use the following to build.gradle
:
implementation("io.quarkus:quarkus-hibernate-validator")
Built-In Validators
The commonly used validators are available as annotations that can be easily added to the data object. In our House data object, we need to ensure the number property should not be null, and the street should not be blank. We will use the annotations @NotNull
and @NotBlank
:
class House {
@NotNull
int number;
@NotBlank(message = "House street cannot be blank")
String street;
String city;
String state;
String type;
}
To validate the data object in a REST API, it is necessary to include the @Valid
annotation. By doing so, there is no need for manual validation, and any validation errors will result in a 400 HTTP response being returned to the caller:
@Path("/house")
public String createHouse(@Valid House house) {
return "Valid house received";
}
Custom Validation
There are several scenarios in which the default validations are insufficient, and we must implement some form of custom validation for our data. In our example, the House data is supported only in California (CA) and Nevada (NV). Let’s create a validator for this:
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.FIELD
})
@Constraint(validatedBy = StateValidator.class)
public @interface ValidState {
String message() default "State not supported";
Class<? extends Payload>[] payload() default {};
Class<?>[] groups() default {};
}
Getting into the details:
- The name of the validator is
ValidState
. In the class validation, this can be used as@ValidState
. - The default error message is added to the
message()
method. - This annotation is validated by
StateValidator.class
and is linked using the@Constraint
annotation. - The
@Target
annotation indicates where the annotation might appear in the Java program. In the above case, it can be applied only toFields
. - The
@Retention
describes the retention policy for the annotation. In the above example, the annotation is retained during runtime.
The validation logic in the StateValidator
class:
public class StateValidator implements ConstraintValidator<ValidState, String> {
List<String> states = List.of("CA", "NV");
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && states.contains(value);
}
}
The custom validator @ValidState
can be included in the House class:
class House {
@NotNull
int number;
@NotBlank(message = "House street cannot be blank")
String street;
String city;
@ValidState
String state;
String type;
}
Testing
In software development, unit testing is a crucial component that offers several benefits, such as enhancing code quality and detecting defects early in the development cycle. The Quarkus framework provides a variety of tools to help developers with unit testing.
Unit testing the custom validator is simple as Quarkus allows us to inject the validator and perform manual validation on the House object:
@QuarkusTest
public class HouseResourceTest {
@Inject
Validator validator;
@Test
public void testValidState() {
House h = new House();
h.state = "CA";
h.number = 1;
h.street = "street1";
Set<ConstraintViolation<House>> violations = validator.validate(h);
System.out.println("Res " + violations);
assertEquals(violations.size(), 0);
}
@Test
public void testInvalidState() {
House h = new House();
h.state = "WA";
h.number = 1;
Set<ConstraintViolation<House>> violations = validator.validate(h);
assertEquals(violations.size(), 1);
assertEquals(violations.iterator().next().getMessage(), "State not supported");
}
}
Conclusion
Quarkus is a robust, well-written framework that provides various built-in validations and supports add custom validation. Validators provide a clean and convenient way to perform REST API validation, which, in turn, supports the DRY methodology. Validation plays an increasingly crucial role in microservices architecture because every service defines and requires the validation of the data it processes. The above article describes a process to use built-in and custom validators.
Opinions expressed by DZone contributors are their own.
Comments