🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Learn how to define and apply custom bean validation in Spring Boot using custom annotations and ConstraintValidator. Includes real-world example and best practices.
Why Custom Validation?
Spring Boot supports many built-in validations (like @NotBlank, @Email, etc.).
But if you have business-specific rules, like:
- Username must start with “USR”
- Age must be a prime number
- ZIP code must match a certain region
➡️ You’ll need a custom validator.
🛠️ Step-by-Step: Create a Custom Validator
Let’s create a custom annotation called @StartsWithUSR to validate usernames.
✅ Step 1: Add spring-boot-starter-validation
If you’re not already using it, add this dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>✅ Step 2: Create Custom Annotation
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = StartsWithUSRValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StartsWithUSR {
String message() default "Username must start with 'USR'";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}✅ Step 3: Create the Validator Class
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class StartsWithUSRValidator implements ConstraintValidator<StartsWithUSR, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && value.startsWith("USR");
}
}✅ Step 4: Use Custom Annotation in DTO or Entity
public class UserRequest {
@StartsWithUSR
private String username;
private String email;
// Getters and Setters
}✅ Step 5: Create Controller and Validate Input
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody @Valid UserRequest request) {
return "User created: " + request.getUsername();
}
}✅ Step 6: Test with Invalid Request
Send a POST request like:
{
"username": "admin",
"email": "admin@example.com"
}You’ll get:
{
"timestamp": "2025-02-25T10:00:00.000+00:00",
"status": 400,
"errors": [
"Username must start with 'USR'"
]
}✅ Validation is working!
Best Practices

Example: More Custom Validations You Can Build

Final Thoughts
Creating a custom bean validation in Spring Boot is simple and powerful:
- ✅ Annotate with
@Constraint - ✅ Implement
ConstraintValidator - ✅ Apply to your models
- ✅ Let Spring handle validation automatically
This approach helps you enforce business rules consistently and keeps your code clean and declarative.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment