DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Spring Boot, Quarkus, or Micronaut?
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Four Essential Tips for Building a Robust REST API in Java

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • Enforcing Architecture With ArchUnit in Java
  • The End of “Good Enough Agile”
  1. DZone
  2. Coding
  3. Java
  4. Custom Validators in Quarkus

Custom Validators in Quarkus

This article provides an overview of validators in the Quarkus Java framework and delves deeply into custom validators with examples

By 
Aashreya Shankar user avatar
Aashreya Shankar
·
Mar. 15, 23 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
13.9K Views

Join the DZone community and get the full member experience.

Join For Free

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).
Java
 
class House {

	String number;
	
	String street;

	String city;

	String state;

	String type;

}


And the REST API:

Java
 
@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:

XML
 
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-validator</artifactId>
</dependency>


For Gradle-based projects, use the following to build.gradle:

Java
 
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:

Java
 
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:

Java
 
@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:

Java
 
@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 to Fields.
  • 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:

Java
 
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:

Java
 
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:

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

API Quarkus REST House (operating system) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • Spring Boot, Quarkus, or Micronaut?
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Four Essential Tips for Building a Robust REST API in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!