Skip to content

Spring Boot Validation Custom

DodaTech 1 min read

In this tutorial, you'll learn about Fix Spring Boot Custom Validator Not Triggering. We cover key concepts, practical examples, and best practices.

The Problem

Your custom @Constraint annotation does not invoke the validation logic.

Quick Fix

Define @Constraint annotation

Wrong:

@Target(FIELD)
@Retention(RUNTIME)
public @interface ValidPassword { }

Output:

No validation logic

Right:

@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
public @interface ValidPassword {
    String message() default "Invalid password";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Output:

Constraint validator defined

Implement ConstraintValidator

Wrong:

public class PasswordValidator {
    // Does not implement interface
}

Output:

Validator not invoked

Right:

public class PasswordValidator implements ConstraintValidator<ValidPassword, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) { return true; }
}

Output:

Validator invoked

Apply custom annotation

Wrong:

// Custom annotation not used

Output:

No validation

Right:

@ValidPassword
private String password;

Output:

Custom validation triggered

Prevention

  • Define @Constraint with validatedBy
  • Implement ConstraintValidator interface
  • Apply the custom annotation to fields

Common Mistakes with boot validation custom

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' causing stack overflow on large lists

These mistakes appear frequently in real-world SPRING code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why is my custom validator not triggered?

Ensure the @Constraint annotation references the correct validator class and the message/groups/payload are defined.

This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro