by BehindJava

How to enable validations for HTTP POST request body using hibernate bean validations in Spring Boot

Home » springboot » How to enable validations for HTTP POST request body using hibernate bean validations in Spring Boot

In this tutorial we are going to learn about validations in the bean class using hibernate bean validations.

There are various bean validations provided by Hibernate and among them we are going to use few validations in our example for basic understanding.

Firstly, we need to add the following dependency in pom.xml.

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

And add these message configuration properties in application.properties under src/main/resources in the project folder structure.

server.error.include-message=always
server.error.include-binding-errors=always

After this we need to add @Valid in the method arguments before @RequestBody of the HTTP POST method which enables the validations for the bean class or model class specified in the method.

@Valid: Marks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are be validated when the property, method parameter or method return type is validated.

Sample Code Snippet:

import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.behindjava.tutorial.model.UserModel;

@RestController
@RequestMapping("/users")
public class UserController {

	@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = {
			MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
	public ResponseEntity<UserModel> createUser(@Valid @RequestBody UserModel us) {

		UserModel um = new UserModel();
		um.setEmail(us.getEmail());
		um.setFirstname(us.getFirstname());
		um.setLastname(us.getLastname());
		um.setUserId(us.getUserId());

		return new ResponseEntity<UserModel>(um, HttpStatus.CREATED);
	}
}

Now it’s time to add validations in the model or bean class. For example in our bean class we have following fields defined like firstname, lastname, email, userId for which we can use the following annotations like

@NotNull : The annotated element must not be null. Accepts any type.
@Email: The string has to be a well-formed email address. Exact semantics of what makes up a valid email address are left to Jakarta Bean Validation providers. Accepts CharSequence.
@Size: The annotated element size must be between the specified boundaries (included). After specifying the required annotation, we can specify the error message with the arguments of the annotation as shown in the below example.

Sample Code Snippet:

import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class UserModel {
	@NotNull(message="First Name cannot be Empty")
	private String firstname;
	@NotNull(message="Last Name cannot be Empty")
	private String lastname;
	@NotNull(message="Email cannot be Empty")
	@Email
	private String email;
	@NotNull(message="User Id cannot be Empty")
	@Size(min=6,max=6, message="User Id must be six lettered Alphanumeric")
	private String userId;
	
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
}

Now we will start our Spring Boot application and sends the HTTP POST request using postman. To check the validations, Im sending userId as rk001 which is only a 5 lettered alphanumeric,and the request fails and shows the custom error message defined by us in the bean class.

title

This request failed since we have a validation for userId where UserId must be a six lettered Alphanumeric values. Likewise, you can try exploring all the available validations.

Previous                                                                                                               Next