Customizing Validation in Spring Boot: How to Create Your Own Constraints

24 / Jan / 2023 by Muskan Lama 0 comments

Customizing Validation in Spring Boot: How to Create Your Own Constraints 

By developing unique constraint annotations and validator classes for Spring Boot, customized validation can be implemented.Here we can show more than one validation error messages
The general steps to build a custom validator in Spring Boot are as follows:

STEP 0 : Add dependency in pom.xml

STEP 1 : Make your own constraint annotations
This annotation will be used to highlight fields that need to be validated.
The annotation needs to be tagged with @Constraint and should be linked to a Validator class. Here I am using phone number validation.

STEP 2: The creation of a validator class
This class should include methods for validating the annotated fields and should implement the Constraint Validator interface.

STEP 3 : Fields that require validation should be annotated with a special constraint
This can be achieved by adding the custom constraint annotation to the
class fields like here in contact.

STEP 4 : Use @Valid annotation in controller

The @Valid annotation from Spring can be used to force object validation by adding it to a method argument or request body.
If any constraints are broken, Spring will automatically validate the object and deliver a list of problems.

STEP 5 : Make a class that will display error message along with certain other validation errors

To get the error message properly create a class to get and bind the validation errors.We have to catch the error messages from exceptions and attach that with our own format of response and return the same to the client.

STEP 6: Make a custom handler to display validation error message

Make a class that has @ControllerAdvice annotation at class level and extends ResponseEntityExceptionHandler class.Override the handleMethodArgumentNotValid() method to show valid error message.This will display more than one validation errors .

STEP 7 : Now you can test it locally !

You can create more validation like unique email,password match and so on….

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *