Search⌘ K
AI Features

Custom Validator

Explore how to create custom validators in Spring Boot with Thymeleaf to perform complex validations such as ensuring unique user emails. This lesson guides you through making annotations, injecting services, and managing error messages to enhance your application's form handling capabilities.

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:

Java
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 {};
}
...