Spring Boot Validation Tutorial With Example

Spring Boot Validation is a feature of the Spring Framework that allows you to validate user input in your application. Spring Boot Validation uses the Java Bean Validation API, which provides a number of built-in constraints that you can use to validate the properties of your objects.

But why API validation is essential?

API request validation is the crucial step in ensuring that client requests align with the API specifications laid out by the API developers. To avoid unexpected/wrong errors as well as slow/invalid responses, API requests should be validated first for correctness before being progressed further.

BUT..It is very tedious task to implement request validation framework.

Here Spring validator can help you. Spring Boot provides excellent support straight out of the box for validating user input. Hibernate validator is used by Spring Boot to validate Java bean field values.

In this tutorial, we will take a look at the spring validator and how to create a custom validator for the bean validation.

To demonstrate the validators concept in spring boot, we will take a look at a few examples.

Spring Boot Validation Tutorial With Example

@Entity
@Table(name = "user_details")
public class User {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int user_id;
	
	private String user_name;
	
	private String password;
	
	private String email;
	
	private String contact_number;

Let’s take an example of a User entity class. The user entity has many properties (columns in the database) like id, user name, password, email, and contact number.

How you will make sure that the client shouldn’t provide any unexpected or empty value for those properties. For those types of validation, we can use annotations provided by Hibernate validators (JSR-380).

Hibernate validators in Spring Boot

Hibernate Validator is a library that provides support for the Java Bean Validation API in the Hibernate framework. Hibernate Validator allows you to define constraints on the properties of your objects and automatically validate them at runtime.

Hibernate validators offer a few annotations that can be used with bean property for validation purposes.

To use Spring Boot Validation in your application, you first need to add the spring-boot-starter-validation dependency to your project. This will enable the validation features of Spring Boot and allow you to use the Java Bean Validation API in your application.

Spring boot by default add hibernate validator’s dependency and configure it on the classpath. Therefore, we don’t have to write any code to add hibernate validator into our project. So, Let’s change the above User class and add a constraint called <code>@NotEmpty</code> to ensure that the user_name property is not empty:

package com.codedelay.rest.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;

import com.codedelay.rest.validation.ContactNumberValidation;
import com.codedelay.rest.validation.Password;

@Entity
@Table(name = "user_details")
public class User {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int user_id;
	
	@NotEmpty(message = "Please enter a user name")
	private String user_name;
	
	@NotEmpty(message = "Please enter the password")
	private String password;
	
	@NotEmpty(message = "Please enter the email")
	private String email;
	
	@NotEmpty(message = "Please provide contact number")
	private String contact_number;

	public int getUser_id() {
		return user_id;
	}

	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}

	public String getUser_name() {
		return user_name;
	}

	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getContact_number() {
		return contact_number;
	}

	public void setContact_number(String contact_number) {
		this.contact_number = contact_number;
	}
}

Spring Boot Validation will automatically validate the input and check that it satisfies the constraints that you have defined. If any of the constraints are violated, Spring Boot Validation will return an error message to the user.

The above annotation doesn’t enable hibernate bean validation automatically.

How to enable Hibernate Bean Validation

There are two ways to enable bean validation.

  1. You can add <code>@Valid</code> (javax.validation) before request body.
  2. You can add <code>@Validated</code> above class Name

Enable Bean Validation using @Valid example

<code>UserController.java</code>

@PostMapping("/add")
	@ResponseStatus(HttpStatus.CREATED)
	public User addUser(@Valid @RequestBody User user) {
		return mService.addUser(user);
	}

Now if you trigger HTTP POST request, then <code>MethodArgumentNotValidException</code> will occur and HTTP 400 Bad Request result will be returned by Spring.

But in the above scenario, spring won’t provide an error message along 400 code. To provide a clear error message let’s override <code>handleMethodArgumentNotValid</code> in <code>GlobalExceptionHandler</code>.

@Override
protected ResponseEntity &amp;lt; Object &amp;gt; handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
  HttpHeaders headers, HttpStatus status, WebRequest request) {

  Map &amp;lt; String, Object &amp;gt; body = new LinkedHashMap &amp;lt; &amp;gt; ();
  body.put("timestamp", new Date());
  body.put("status", status.value());

  //Get all errors
  List &amp;lt; String &amp;gt; errors = ex.getBindingResult()
    .getFieldErrors()
    .stream()
    .map(x -&amp;gt; x.getDefaultMessage())
    .collect(Collectors.toList());

  body.put("errors", errors);
  return new ResponseEntity &amp;lt; &amp;gt; (body, headers, status);
}

Now let’s see the error message when we provide the empty user name.

{
  "timestamp": "2019-07-31T09:17:30.679+0000",
  "status": 400,
  "errors": [
    "{user.name.invalid}"
  ]
}

Enable Bean Validation using @Validated at class Level

To enable bean validation in a Spring Boot application using the @Validated annotation at the class level, you can follow these steps:

  1. Add the spring-boot-starter-validation dependency to your project. This will enable the validation features of Spring Boot and allow you to use the Java Bean Validation API in your application.
  2. Add the @Validated annotation to the class that you want to enable bean validation for. This will enable bean validation for all methods in the class.
  3. Add the @Valid annotation to the method parameters that you want to validate. This will cause Spring Boot Validation to validate the input for these parameters and check that it satisfies the constraints that you have defined.

Here is an example of how you can use the @Validated and @Valid annotations in a Spring Boot application to enable bean validation at the class level:

@RestController
@Validated
public class UserController {
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
        // Save the user and return the response...
    }
}

n this example, we use the @Validated annotation to enable bean validation for the UserController class. We then use the @Valid annotation on the createUser method to enable bean validation for the user parameter.

When a user attempts to create a new user by calling the createUser method, Spring Boot Validation will automatically validate the input and check that it satisfies the constraints that we have defined for the User class. If any of the constraints are violated, Spring Boot Validation will return an error message to the user.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.