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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. Custom Validators in Quarkus

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.

Aashreya Shankar user avatar by
Aashreya Shankar
·
Mar. 15, 23 · Tutorial
Like (2)
Save
Tweet
Share
4.19K 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.

Popular on DZone

  • Key Elements of Site Reliability Engineering (SRE)
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam
  • Front-End Troubleshooting Using OpenTelemetry
  • Steel Threads Are a Technique That Will Make You a Better Engineer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: