Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Create a Custom Validator Annotation in Spring Boot
📖 Scenario: You are building a Spring Boot application that needs to validate user input. The default validators do not cover your specific rule, so you want to create a custom validator annotation to check if a string contains only uppercase letters.
🎯 Goal: Build a custom validator annotation called @Uppercase that can be applied to string fields. This validator should check if the string contains only uppercase letters.
📋 What You'll Learn
Create a custom annotation called @Uppercase
Create a validator class that implements ConstraintValidator
Use the custom annotation on a field in a model class
Ensure the validator checks if the string is uppercase only
💡 Why This Matters
🌍 Real World
Custom validators are useful when built-in validation rules do not cover your specific business requirements, such as enforcing uppercase-only codes or special formats.
💼 Career
Knowing how to create and use custom validation annotations is important for backend developers working with Spring Boot to ensure data integrity and user input validation.
Progress0 / 4 steps
1
Create the @Uppercase annotation
Create a custom annotation called @Uppercase with these exact elements: annotate it with @Constraint(validatedBy = UppercaseValidator.class), @Target({ElementType.FIELD}), @Retention(RetentionPolicy.RUNTIME), and include a message element with default value "Must be uppercase". Also include Class>[] groups() default {}; and Class extends Payload>[] payload() default {};.
Spring Boot
Hint
Remember to import jakarta.validation.Constraint and set the validatedBy to your validator class.
2
Create the UppercaseValidator class
Create a class called UppercaseValidator that implements ConstraintValidator<Uppercase, String>. Override the isValid method to return true if the input string is null or contains only uppercase letters (use input.equals(input.toUpperCase())).
Spring Boot
Hint
Check for null first, then compare the string to its uppercase version.
3
Use @Uppercase on a model field
Create a class called User with a private string field called code. Annotate the code field with @Uppercase. Include public getter and setter methods for code.
Spring Boot
Hint
Remember to add the @Uppercase annotation exactly above the code field.
4
Complete the Spring Boot validation setup
In the User class, add the @Validated annotation on the class level to enable validation. Also, add the @NotNull annotation on the code field to require a value.
Spring Boot
Hint
Add @Validated on the class and @NotNull on the code field to complete validation setup.
Practice
(1/5)
1. What is the main purpose of creating a custom validator annotation in Spring Boot?
easy
A. To define your own validation rules reusable across your application
B. To replace built-in annotations like @NotNull completely
C. To automatically generate database tables
D. To handle HTTP requests in controllers
Solution
Step 1: Understand the role of custom validator annotations
They allow you to create your own rules for validating data beyond built-in checks.
Step 2: Identify the main benefit
These annotations keep validation logic clean and reusable across different parts of your app.
Final Answer:
To define your own validation rules reusable across your application -> Option A
Quick Check:
Custom validator = reusable validation rules [OK]
Hint: Custom validators create reusable rules, not replace built-ins [OK]
Common Mistakes:
Thinking custom validators replace all built-in annotations
Confusing validation with database or HTTP handling
Assuming custom validators auto-generate code
2. Which of the following is the correct way to declare a custom validator annotation interface in Spring Boot?
easy
A. @Validator class MyValidator { String message() default "Invalid"; }
B. class MyValidator { String message() default "Invalid"; }
4. You wrote a custom validator but it always passes validation even for invalid data. Which of these is the most likely cause?
medium
A. The annotation interface is missing the @Target annotation
B. The isValid method always returns true regardless of input
C. The validator class does not implement ConstraintValidator
D. The message() method in the annotation returns an empty string
Solution
Step 1: Understand the role of isValid method
This method contains the validation logic and must return true only for valid inputs.
Step 2: Identify why validation always passes
If isValid always returns true, invalid data will pass unchecked.
Final Answer:
The isValid method always returns true regardless of input -> Option B
Quick Check:
isValid controls validation result; always true means always pass [OK]
Hint: Check isValid method return values first when validation fails [OK]
Common Mistakes:
Forgetting to implement ConstraintValidator interface
Missing @Target causes compile warnings but not always validation failure
Empty message() affects error text, not validation logic
5. You want to create a custom validator annotation @StartsWith that checks if a string starts with a given prefix. Which combination of elements is required to implement this correctly?
hard
A. An annotation interface with a String prefix() method, a validator class implementing ConstraintValidator<StartsWith, String>, and overriding isValid to check the prefix
B. An annotation interface with int length(), a validator class implementing Validator, and overriding validate to check length
C. A class annotated with @Component that implements ConstraintValidator without an annotation interface
D. An annotation interface with String suffix(), a validator class implementing ConstraintValidator<EndsWith, String>, and overriding isValid to check suffix
Solution
Step 1: Define the annotation interface with a prefix parameter
The annotation must declare a method String prefix() to accept the prefix value.
Step 2: Implement the validator class correctly
The validator class must implement ConstraintValidator<StartsWith, String> and override isValid to check if the string starts with the given prefix.
Final Answer:
An annotation interface with a String prefix() method, a validator class implementing ConstraintValidator<StartsWith, String>, and overriding isValid to check the prefix -> Option A