0
0
Spring Bootframework~30 mins

Custom validator annotation in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
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[] payload() default {};.
Spring Boot
Need a 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
Need a 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
Need a 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
Need a hint?

Add @Validated on the class and @NotNull on the code field to complete validation setup.