Create Custom Bean Validation Annotation in Spring Boot

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare