Home » Framework » How to do Bean Validation in Spring Boot

How to do Bean Validation in Spring Boot

We can do Bean Validation or Pojo validation in Spring Boot in several ways. But the most efficient way is doing it with the default starter validator in Spring Boot. In Spring Boot starter validator mostly covers all of the common validations through annotations.

We can use constraints from javax.validation in the form of annotations that can be placed on the field, method, and class level to do validation. So let's start to see the implementation of that.

We have to create a new project in Spring Initializr with the basic maven dependencies spring web, and spring boot starter validation. Here I used the below bean to validate the fields.

package com.tipstocode.model;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import com.sun.istack.internal.NotNull;
import com.tipstocode.validator.custom.Mobile;
public class Profile {
	
	//Fields
	@NotBlank
        @NotNull
	private String firstName;
	
	@NotBlank
        @NotNull
	private String lastName;
	
	@NotBlank
        @NotNull
	@Email
	private String emailId;	
        //Getters and Setters
}

Maven dependency for spring boot starter validation is

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

We don't need to mention the version for maven dependency spring boot automatically binds with its version. You can use the latest version also.

In the profile bean, I have used some basic annotations for example. But there are several annotations are there. You can see all that here. Now let's go to the validation part. Validation we can do it on the bean of POST method and do it on request parameters of GET method.

Validation of json from post method or request body

Spring automatically converts the JSON from request body to bean. So here we can see how to do bean validation at the controller level. The below code is used to achieve that.

@RestController
public class ProfileController {
@RequestMapping(value = "/saveprofile", method = RequestMethod.POST )
public ResponseEntity<String> saveProfile(@Valid @RequestBody Profile profile) {		
return ResponseEntity.ok("valid");
}
}

In the above snippet @Valid method is placed before the @RequestBody to validate the Profile Bean. In profile bean, I have used @NotNull, @NotBlank, and @Email constraints. So it validates at the controller level and returns a response.

@NotNull validates whether the field is null or not. @NotBlank validates the field is empty or blank and @Email validates whether the field is in the format of email or not. if we put @Valid before the request body then it validates the profile bean with validation constraints.

If validations are successful then it returns valid with HTTP 200 status and if fails it throws the MethodArgumentNotValidException. But by default spring translate this exception to 400 bad requests.

Validation of Request Parameters

The below code validates request parameters at the controller level

@RestController
@Validated
public class ProfileController {
@RequestMapping(value = "/getprofilebyid", method = RequestMethod.GET )
public ResponseEntity<String> getProfileById(@RequestParam("id") @NotBlank String id) 
{	
return ResponseEntity.ok("valid");
}

From the above get method, we can get profile details by passing id as a request parameter. We can validate id should not be null for that. So we need to put the @NotBlank constraint before the parameter id. While using a constraint on the method level please make sure to put @Validated annotation at the class level.

If the validation successful then it returns valid with HTTP status 200. If failed it throws the ConstraintViolationException with HTTP status 500. Spring translates this as Internal Server Error. But we have to send this as meaningful Http 400 bad request as a response. We can see this in how to send the proper way of response to the client.

Here we used some of the basic annotations for bean validation. But in some times it is not sufficient to validate some fields like Ip Address, Mobile Number and etc. So we can create our own validator to achieve that. Here you can see how to create a custom validator in spring boot.

Download the source code from GitHub

Leave a Reply

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