Monday, November 18, 2024
Google search engine
HomeLanguagesJavaSpring Boot – Data and Field Validation using jakarta.validation.constraints

Spring Boot – Data and Field Validation using jakarta.validation.constraints

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.

RELATED ARTICLES

Most Popular

Recent Comments