How to customize request validation in Spring boot using Java Bean Validation

Overview

Prerequisites

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Creating Custom Constrains

Validator

Using the New Constraint

Validating Request

Customizing Invalid Request Response

DEMO!

Image for post
Image for post

Hope you have found this tutorial helpful and you can integrate this technique in your next project. You can find the code for this tutorial on GitHub.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store