

Custom Validators in Quarkus
source link: https://dzone.com/articles/custom-validators-in-quarkus
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Custom Validators in Quarkus
In this article, readers will use a tutorial to learn how to create a custom validator in the Quarkus Java framework, with code examples and unit tests.
Quarkus 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.
Recommend
-
24
Pascal Thellman is CMO at Bounty0x, a simple service for earning crypto, and an advisor at PolyGrowth, a crypto PR firm. — As proof-of-stake (PoS) networks gear up in an effort to compete with proof-of-w...
-
27
Weekly writings about Programming using JVM languages such a Kotlin, Groovy, Java, and concepts such a scalability, architecture and security.
-
28
README.md govalidator
-
28
README.md protoc-gen-validate (PGV) This project is currently in alpha. The API should be considered unstable and likely...
-
17
Ethereum 2.0 single client testnets have been running for weeks with restarts and the like, but now they seem to have reached a more stable stage. One of them is that of Prysmatic Labs which went out on January...
-
29
title date category tags YIL: Rails validators don't change parameter type 2020-04-07T09:04 rails validation...
-
29
本文是由以太坊2.0协调员Danny Ryan发布于以太坊官方博客上的,原文为《 以太坊2.0的现状 》(2020年6月)。在这篇文章中,Danny Ryan介绍了以太坊2.0...
-
9
How to test custom prop validators in Vue.jsWritten by Rolf Haug In this article, I will show you how you can test props and custom prop validators in a simple and performant way, without spying on the console error. Te...
-
16
ConversationThe launch of the #Eth2 Beacon Chain is characteristic of the emergent, open-source ethos that attracts so many to Ethereum in the first place. More than 27,000 validat...
-
6
Tezos Israel Develops Hardware Device to Protect Network Validators’ Staked AssetsAn Israel-based innovation hub focused on the proof-of-stake blockchain network Tezos is bringing out a security...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK