Spring Boot Part 1 — Creating Custom Validator Annotation

Ye Lynn
3 min readAug 14, 2022

In spring boot, when we need to receive data from user inputs, we can use automatic deserialization provided in spring. This also comes with the needs for some validation check. While spring-boot-starter-validation provides the basic need for validation checks such as Min, Max, NotNull, etc., sometimes we need to create our own validator to fulfil our needs.

This tutorial will show how to create our own simple validator annotation. We will use the example of validating if the input is even number or not.

1. Dependencies

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

This dependency needs to be added in pom.xml to provide us with the dependencies which will be needed to create our own custom validator annotation.

2. Controller

@RestController
@RequestMapping("/custom-validator")
@Validated
public class Controller {
@GetMapping("/even-number/{number}")
public String checkEvenNumber(@PathVariable @EvenNumber(message = "Only even number is accepted") Integer number) {
return String.format("Even number provided is: %d", number);
}
}

Let’s first create a controller that will accept a number from user input with path variable, check if the number is even, then return the String “Even number provided is “ if it pass the validation.

Note: if you get import error for @EvenNumber annotation, don’t worry. We will create that annotation in the next step.

3. Create Custom Annotation

@Constraint(validatedBy = EvenNumberValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EvenNumber {
String message() default "Not an even number";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

The above snippet will create a custom annotation with name EvenNumber which can be used in Field or Parameter and accept message parameter(optional) to return if the validation is not success. You can customize the default message by providing the custom message when utilizing the annotation as shown in our controller.

Next, we will need to create a validator which will implement our validation logic.

Note: EvenNumberValidator.class from Line 1 is the validator we are going to create in step 4.

4. Create Validator Logic

public class EvenNumberValidator implements ConstraintValidator<EvenNumber, Integer> {

@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return value % 2 == 0;
}
}

This validator implements isValid method which will accept Integer value and return true if the value is even number. Otherwise, it will return false.

Note: the validator implements ConstraintValidator interface.

5. Testing

That’s it. How easy !! Now it’s time to test.

The number provided is 4(even), so the controller works as expected
The number provided is 3(odd), so the validation throws the error and the rest of the logic won’t work

Note: if you want to customize the error response with your own format, I’ll create another article how to implement it.

The source codes are available on github: https://github.com/yelynn1/springboot-demo/tree/main/src/main/java/com/yelynn/springbootdemo/customvalidator

--

--