Sitemap

Member-only story

How to Create Custom Bean Validation 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.

2 min readMar 25, 2025

--

Let’s go step-by-step to understand how to define and use a custom validation annotation.

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…

--

--

No responses yet