creating custom spring validator
Spring boot comes with lots of validation out of the box, Min
, Max
, NotNull
. But, those are not enough as custom validations are important and needed.
When to use custom spring validator
When there is specific business logic that needs to be validated, custom validation will be to the rescue.
An example of creating a custom spring validator can be the following scenario. On your application there is a registration page.
Let’s say you have a survey sent out before registration and you want a user to fill out a survey using their email associated with it before registration.
When the user comes to your website for registration, one criteria as validated user is a completion of the survey. Here, you can create this validator and use it on more than one forms.
What do I need for custom spring validator
A basic knowledge of java and spring framework is good enough for this. Also make sure if it is worth creating spring custom validator. This is also the same if you are considering custom spring boot validator
Custom Spring validator example, spring validator tutorial
Let us extend the above example and work on it. We would like to have a unique email to be read from database as custom spring validator.
Let’s call it UniqueEmailValidator
. This is will be checked mostly during registration and we can assume it can also used in a couple of other places.
First, we need to create a custom target interface
/**
* Custom email validation
* Checks if the email already exists or not.
*
* @author Kaleb Woldearegay
*
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmailValidator.class)
public @interface UniqueEmail {
String message() default "{Email already exists}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
You can find the full code on github here.
Then we will need a concrete class that implements the interface
/**
* Custom email validation. Check if the provided email is unique or not.
* @author Kaleb Woldearegay
*
*/
@Configurable
public class UniqueEmailValidator implements ConstraintValidator {
private MemberService memberService; //this is injected to the class
public UniqueEmailValidator() {}
@Autowired
public UniqueEmailValidator(MemberService memberService) {
this.memberService = memberService;
}
public void initialize(UniqueEmail constraint) {
}
public boolean isValid(String email, ConstraintValidatorContext context) {
if (email == null) {
return false;
}
//actual logic of search for the member goes here..
Optional member = this.memberService.findByEmail(email);
return !member.isPresent();
}
You can see the full class here
The important part of the implementation is the isValid
one. That should return the boolean outcome.
That is it, now you have the a full-fledged custom spring validator in created.
You can use it using the annotation @UniqueEmailValidator
in your controller or wherever you need to validate.
If you have any questions or comments, let me know.