Spring Boot - Data and Field Validation using jakarta.validation.constraints
Last Updated :
04 Jan, 2025
Every Java-based application must include bean validation to make sure that the data input complies with predefined rules and limitations. A strong framework for validating JavaBeans is provided by Jakarta Bean Validation 3.0, which is a component of the Jakarta EE platform. In this post, we'll look at how to use and integrate Spring Boot applications with Jakarta Bean Validation 3.0. We'll delve into its fundamental ideas and offer real-world examples to show how to use it.
Getting Started
1) Use an existing Spring Boot project or start a new one.
2) In your project's build configuration file (pom.xml for Maven or build.gradle for Gradle), add the requirement for Jakarta Bean Validation 3.0.
For Maven:
XML
<dependency>
<groupId>org.glassfish.jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.0</version>
</dependency>
For Gradle:
XML
implementation 'org.glassfish.jakarta.validation:jakarta.validation-api:3.0.0'
3) Create a model class for your spring project that will include annotations for your data.
Java
package com.example.demo;
import jakarta.validation.constraints.*;
class TestingValidation {
public interface AllLevels {
}
public interface Junior {
}
public interface MidSenior {
}
public interface Senior {
}
@Size(min = 5, max = 20,
message
= "Name must be between 5 and 20 character")
@Pattern(regexp = "[^0-9]*",
message = "Name must not contain numbers")
@NotBlank(message = "Name is mandatory field")
String name;
@Min(
value = 5, groups = Junior.class,
message
= "Junior level requires at least 5 years of experience")
@Min(
value = 10, groups = MidSenior.class,
message
= "Mid-Senior level requires at least 10 years of experience")
@Min(
value = 15, groups = Senior.class,
message
= "Senior level requires at least 15 years of experience")
int exp;
@AssertTrue(message = "You are not admin")
boolean isAdmin;
@Pattern(regexp = "\\d{10}",
message
= "Mobile number must have exactly 10 digits")
String mobileNumber;
public TestingValidation(String name, int exp,
boolean isAdmin,
String mobileNumber)
{
this.name = name;
this.exp = exp;
this.isAdmin = isAdmin;
this.mobileNumber = mobileNumber;
}
public void dummy()
{
System.out.println("Dummy method running, " + name);
}
}
4) In your controller class, Define Validator and create object of model class.
Java
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.TestingValidation;
import com.example.demo.TestingValidation.Senior;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.ValidatorFactory;
@RestController
public class MainController {
@GetMapping("/")
public List < String > Testing() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
// Creating object
jakarta.validation.Validator validator = factory.getValidator();
TestingValidation ts=new TestingValidation("adarsh123",12,false,"921111110");
// Provide an empty name and
// low experience for demonstration
ts.dummy();
// It will validate each field
Set<ConstraintViolation<TestingValidation>> violations = validator.validate(ts);
// It will validate if provided data is belongs to senior or not
Set<ConstraintViolation<TestingValidation>> violations2 = validator.validate(ts,Senior.class);
// Response List
List<String> Reslist=new ArrayList<String>();
// Will run for loop to see if there are any validation error
for (ConstraintViolation<TestingValidation> violation : violations)
{
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
Reslist.add(violation.getMessage());
}
for (ConstraintViolation<TestingValidation> violation : violations2)
{
System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
Reslist.add(violation.getMessage());
}
return Reslist;
}
}
5) Now when we input invalid data in constructor of model class, It will throw error message to Validator, and You can run a for loop to get the error messages from validator
Output:

Conclusion
In this blog post, we looked at how to use and integrate Spring Boot applications with Jakarta Bean Validation 3.0. We handled validation errors, integrated validation into a controller, and specified validation restrictions using annotations. When paired with the ease of Spring Boot, Jakarta Bean Validation becomes even more effective at assuring data integrity and adherence to set criteria in your Java applications.
Feel free to test out more complicated scenarios and look through the wide selection of validation annotations offered by Jakarta Bean Validation 3.0 to find the right one for your application.
Similar Reads
Spring Boot â Validation using Hibernate Validator Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API)
6 min read
Spring MVC â Handling Form Validation with Spring Validator Form validation is crucial in web applications to ensure that user input is both accurate and appropriate before processing or storing it. In Spring MVC, form validation can be efficiently managed using the Spring Validator interface and annotations. This allows for flexible and robust validation me
7 min read
Request Body and Parameter Validation with Spring Boot For the Spring-Based RESTful Application, it is important to handle the incoming API requests and meet the expected format criteria. To handle this situation, we used @RequestBody, @RequestParam, and @Valid Annotation in the Spring Boot Application to validate the required format of the incoming req
4 min read
Spring Boot - How to Access Database using Spring Data JPA Spring Data JPA is a robust framework that simplifies the implementation of JPA (Java Persistence API) repositories, making it easy to add a data access layer to the applications. CRUD (Create, Retrieve, Update, Delete) operations are the fundamental actions we can perform on a database. In this art
5 min read
Spring Bean Validation - JSR-303 Annotations In this article, we'll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate
6 min read
Maven Project - Phone Number Validations and Testing via JUnit Any web/mobile/console application should be error-free and hence it has to undergo a lot of validations. In this article, let us see how to validate phone numbers with and without country codes and test the same via JUNIT to check whether the given testing phone numbers are correct or not. Via a ma
4 min read
Spring Boot - Transaction Management Using @Transactional Annotation The @Transactional annotation is the metadata used for managing transactions in the Spring Boot application. To configure Spring Transaction, this annotation can be applied at the class level or method level. In an enterprise application, a transaction is a sequence of actions performed by the appli
9 min read
Returning Errors Using ProblemDetail in Spring Boot In a Spring Boot application, error handling is an important aspect of providing a robust and user-friendly API. Traditionally, Spring Boot has provided various methods like @ExceptionHandler, ResponseEntityExceptionHandler, and @ControllerAdvice for handling exceptions. With Spring Framework 6 and
7 min read
Spring Data JPA - @Table Annotation Spring Data JPA is a powerful framework that simplifies database interactions in Spring Boot applications. The @Table annotation in JPA (Java Persistence API) is used to specify the table name in the database and ensure proper mapping between Java entities and database tables. This is especially use
3 min read
Spring Data JPA - @Id Annotation Spring Data JPA is a important part of Spring Boot applications, providing an abstraction over JPA (Java Persistence API) and simplifying database interactions. JPA is a specification that defines a standard way to interact with relational databases in Java, while Hibernate is one of the most widely
3 min read