Hello! Let's get started with today's lesson.
In our previous lessons, we set up robust foundations for our application. We applied standard bean validation annotations like @NotNull and @Size to our DTOs, created a global exception handler with @ControllerAdvice to return clean error responses, and implemented structured JSON logging to trace request flows.
This setup works perfectly for common validation needs. But what happens when your business logic is more specific? For example, a blog post slug must be in kebab-case, a username must not contain reserved words, or a product SKU must follow a unique internal format. These are rules that standard annotations can't cover.
This brings us to today's learning outcome: Create a custom validation annotation (e.g., for a username) to enforce a specific business rule. We'll build our own annotation from scratch, encapsulating domain-specific logic into a reusable, declarative component—a hallmark of professional backend development.
Why Custom Validation?
In the MERN world, you might handle this by writing custom validation logic using a library like Zod with .refine() or Joi with .custom(), or even by creating a dedicated Express middleware. The goal is the same: encapsulate and reuse a specific validation rule.
In Spring, we achieve this in a more structured, type-safe way by creating a custom annotation. This approach keeps our DTOs and controllers clean and declarative, separating the validation rule from the business logic.
The Anatomy of a Custom Validator
Creating a custom validator in Spring involves two key parts:
- The Annotation Interface: This is the custom annotation itself (e.g.,
@ValidSlug). You define it using@interfaceand add a few meta-annotations to configure its behavior and link it to the validator logic. - The Validator Class: This class contains the actual validation logic. It implements the
ConstraintValidatorinterface from the Jakarta Bean Validation API.
The following article provides a concise overview of this structure.
How to Create Custom Validation Annotations in Spring Boot
Before we start coding, let's get a clear picture of the components we need to build. Please read the introductory sections of this article from OneUptime.
Read the sections titled 'The Anatomy of a Custom Validator' and 'Building a Simple Field Validator'. This will give you a solid conceptual framework for the two key components we are about to create.
Hands-On: Creating a @ValidSlug Annotation
For our blog platform, we need to ensure that post slugs (the part of the URL that identifies a post, like /posts/my-awesome-post) follow a specific format. A good slug is crucial for SEO and readability.
Our business rule for a slug will be:
- It must contain only lowercase letters, numbers, and hyphens.
- It cannot start or end with a hyphen.
- Hyphens cannot appear consecutively (e.g.,
my--slug).
A regex for this could be ^[a-z0-9]+(?:-[a-z0-9]+)*$. While we could use the built-in @Pattern annotation, creating a custom @ValidSlug is more expressive and encapsulates the business meaning of "slug" rather than just a regex pattern.
This video provides a fantastic walkthrough of the entire process of creating a custom annotation. We will follow a similar procedure.
Spring Boot Validations Explained | @Valid, Annotations & Custom Validation
Watch this section from the 'Spring Boot Validations Explained' video by The Curious Coder. It demonstrates how to create a custom annotation for phone number validation. We will apply the same steps to create our @ValidSlug annotation.
Watch from 34:08 to 45:14. Pay close attention to the three main parts: creating the annotation interface, implementing the ConstraintValidator, and linking them with @Constraint.
Now, let's implement this in our project.
Step 1: Define the Annotation Interface
First, create a new package for our custom validation components, for example, com.example.blogplatform.validation. Inside this package, create a new annotation file named ValidSlug.java.
package com.example.blogplatform.validation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Constraint(validatedBy = SlugValidator.class) // Link to the validator class
@Target({ ElementType.FIELD, ElementType.PARAMETER }) // Can be used on fields and method parameters
@Retention(RetentionPolicy.RUNTIME) // Must be available at runtime
public @interface ValidSlug {
// Default error message
String message() default "Invalid slug format. Slug must be lowercase alphanumeric with single hyphens.";
// Boilerplate for Bean Validation
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Key Meta-Annotations:
@Constraint(validatedBy = SlugValidator.class): This is the most important part. It tells Spring which class holds the logic for this annotation.@Target: Specifies where you can apply this annotation.FIELDis the most common.@Retention(RetentionPolicy.RUNTIME): Ensures the annotation information is available to the JVM during runtime, which the validation framework needs.
Step 2: Implement the Validator Class
Next, create the SlugValidator.java class in the same package. This class will contain our business rule logic.
package com.example.blogplatform.validation;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
public class SlugValidator implements ConstraintValidator<ValidSlug, String> {
// Regex: lowercase alphanumeric words separated by single hyphens
private static final Pattern SLUG_PATTERN = Pattern.compile("^[a-z0-9]+(?:-[a-z0-9]+)*$");
@Override
public void initialize(ValidSlug constraintAnnotation) {
// We can initialize the validator with attributes from the annotation here,
// but our @ValidSlug annotation has no attributes, so this is empty.
}
@Override
public boolean isValid(String slug, ConstraintValidatorContext context) {
// Let @NotNull handle null values. An optional field should not fail validation here.
if (slug == null || slug.isEmpty()) {
return true;
}
// Return true if the slug matches the pattern, false otherwise.
return SLUG_PATTERN.matcher(slug).matches();
}
}
ConstraintValidator<ValidSlug, String>: This generic signature binds our validator to the @ValidSlug annotation and specifies that it validates fields of type String.
Step 3: Apply the Annotation to a DTO
Finally, let's use our new annotation. Assuming you have a DTO for creating or updating posts, add the slug field and annotate it. Let's imagine a PostRequestDto.
// In your PostRequestDto.java or similar DTO
import com.example.blogplatform.validation.ValidSlug;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class PostRequestDto {
@NotBlank
@Size(min = 3, max = 255)
private String title;
@NotBlank
@Size(max = 65535)
private String content;
@NotBlank
@ValidSlug // Our custom annotation in action!
private String slug;
// Getters and setters...
}
Remember to add the @Valid annotation in your controller to trigger the validation process.
// In your PostController.java
@PostMapping
public ResponseEntity<PostResponseDto> createPost(@Valid @RequestBody PostRequestDto postRequestDto) {
// ... service call
}
Runtime Observation and Debugging
Now for the rewarding part: seeing it work.
- Run the application.
- Open Postman and send a
POSTrequest to your endpoint for creating posts. - Test the failure case: Use a request body with an invalid slug.
{ "title": "My Test Post", "content": "This is some content.", "slug": "This Is Not A Valid Slug" } - Observe the response. You should receive a
400 Bad Request. Thanks to the@ControllerAdvicewe built earlier, the response body should be a structured JSON error pointing directly to theslugfield with our custom message:"Invalid slug format...".

- Test the success case: Now, try a valid slug like
this-is-a-valid-slug. The request should be processed successfully, resulting in a201 Createdor200 OKresponse.
Conclusion
You have successfully created and integrated a custom validation annotation! This is a powerful technique that allows you to build clean, maintainable, and highly expressive APIs by embedding business rules directly into your data model.
Key Takeaways:
- Custom validation is necessary for enforcing domain-specific business rules not covered by standard annotations.
- A custom validator consists of two parts: an annotation interface (e.g.,
@ValidSlug) and a validator class that implementsConstraintValidator. - The
@Constraint(validatedBy = ...)meta-annotation is the critical link between the two parts. - The
isValid()method in the validator class contains the actual logic and returnstruefor valid data andfalsefor invalid data. - Custom validation annotations are triggered by
@Validin the controller and their errors are handled by your@ControllerAdvice, just like standard annotations.
Preview of the Next Lesson:
Currently, our global exception handler catches MethodArgumentNotValidException for all validation failures. But what about other errors, like trying to fetch a post that doesn't exist? That might throw a custom EntityNotFoundException from your service layer. In the next lesson, "Distinguish between application-level exceptions and validation exceptions and handle each accordingly," we will enhance our @ControllerAdvice to handle multiple, specific exception types, allowing us to return different HTTP statuses and error formats for different failure scenarios.