In this post, we look at how to apply bean validation to the input of REST calls in Spring Boot. With bean validation you can validate that the objects passed to your REST end-points are valid and ready to use.
To use Spring validation to validate the input of the REST methods, you need to include the following dependency:
This dependency adds the Hibernate validator to your project. Spring uses this validator to verify that your beans are valid.
Using bean validation
The next step is to apply the validation you need to the fields you want to have validated. In the following examples, I validate that the username is not null and has a minimum length of 2 and a maximum length of 5.
Take a look at the Jakarta specification if you want to know more about validation and the built-in annotations.
Validate input of REST calls
You need to annotate the parameter you want to validate with @Valid. Only parameters with @Valid are checked to see if they are
indeed valid. The
user parameter will be validated in the following example before the method is entered.
createUser method, you can be sure that the
User instance is valid.
Validation on a Record
Starting with Hibernate Validator
8.0.0.Final, you can now validate records in Java. This means you can apply annotations like this:
These instances will be validated like any other.
This post showed you how you can use Spring bean validation with REST end-points. To start with validation, you need to add the spring-boot-starter-validation dependency. Using the Jakarta validation annotations, you can validate the input parameters of your methods.