Custom Validator
Learn how to create custom validations that work for the whole object.
We'll cover the following...
We’ve been using the built-in constraints from the javax.validation.constraints
package until now.
Creating custom validations
When those are not enough, we can create our own custom validation. Such validation can validate a single field or the whole class. Check out the Custom Validator to check if, say, a String contains an XML blog post as an example of a custom validation on a single field.
We will create a custom validator that validates the whole object. For example, it would be good to validate if there is already a known user with the given email address since the email address of each user should be unique.
Create annotation
We start by creating our own annotation:
Press + to interact
package com.tamingthymeleaf.application.user.web;import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE) //<.>@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy = NotExistingUserValidator.class) //<.>public @interface NotExistingUser {String message() default "{UserAlreadyExisting}";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}