Writing a custom validator
55 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite checks the same SKU rule on three request records, and "sale price below price" involves two fields. Built-in annotations cannot say either one cleanly.
A @Sku annotation and its ConstraintValidator
A ConstraintValidator<A, T> is the class that checks annotation A on a value of type T. Its one method, isValid(value, context), returns true when the value is acceptable and false when it breaks the rule.
ShopLite needs the same SKU rule on three request records. Instead of repeating @Pattern three times, you write one @Sku annotation and one validator class. The example shows both, with a demo.
Example 1 · Sku.java, SkuValidator.java, SkuDemo.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/custom/Sku.javapackage com.shoplite.lab.custom;
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;
import jakarta.validation.Constraint;import jakarta.validation.Payload;
@Documented@Constraint(validatedBy = SkuValidator.class)@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE})@Retention(RetentionPolicy.RUNTIME)public @interface Sku {
String message() default "must be 3-20 characters: A-Z, 0-9 or -";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};}
// src/main/java/com/shoplite/lab/custom/SkuValidator.javapackage com.shoplite.lab.custom;
import jakarta.validation.ConstraintValidator;import jakarta.validation.ConstraintValidatorContext;
public class SkuValidator implements ConstraintValidator<Sku, String> {
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return true; } if (value.length() < 3 || value.length() > 20) { return false; } for (char c : value.toCharArray()) { boolean allowed = (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-'; if (!allowed) { return false; } } return true; }}
// src/main/java/com/shoplite/lab/custom/SkuDemo.javapackage com.shoplite.lab.custom;
import java.util.Comparator;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.NotNull;
record NewProductForm(@NotNull(message = "is required") @Sku String sku) {}
public class SkuDemo {
public static void main(String[] args) { try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { Validator validator = factory.getValidator();
for (String sku : new String[] {"MOB-RN13", "kb 1", "AB", "", null}) { String shown = sku == null ? "null" : "\"" + sku + "\""; var problems = validator.validate(new NewProductForm(sku)); String result = problems.stream() .map(ConstraintViolation::getMessage) .sorted(Comparator.naturalOrder()) .reduce((a, b) -> a + "; " + b) .orElse("valid"); System.out.printf("%-12s %s%n", shown, result); } } }}11:04:50.673 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final "MOB-RN13" valid "kb 1" must be 3-20 characters: A-Z, 0-9 or - "AB" must be 3-20 characters: A-Z, 0-9 or - "" must be 3-20 characters: A-Z, 0-9 or - null is required
What this code does
@Constraint(validatedBy = SkuValidator.class)links the annotation to its checker.message,groupsandpayloadmust exist with exactly these types, or Hibernate Validator rejects the annotation.@NotNull(message = "is required") @Skugives one message per problem: a missing SKU is "is required", and anything else that is wrong, the empty string included, gets the SKU message. The lesson on annotations had two messages for""; this pair fixes that.- The first line is Hibernate Validator's INFO log, as in every example of this lesson.
A custom constraint has two parts. The annotation (@interface Sku) carries @Constraint(validatedBy = SkuValidator.class) and three required members: message, groups and payload. The validator class implements isValid.
Copies of @Pattern drift apart: one day someone fixes the message in one copy only. @Sku names the rule once, so a change is one edit and @Sku String sku reads like business language. By convention isValid returns true for null and leaves "is it required?" to @NotNull. The validator class must be public with a public no-argument constructor, because Hibernate Validator creates it by reflection; a package-private class fails with HV000064: Unable to instantiate ConstraintValidator.
Fix the error
Fix the validator class
Read the real error, then pick the line that fixes it.
Validating a record with @Sku fails at run time.
Error
jakarta.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: class com.shoplite.lab.custom.SkuValidator.
Reusing built-in constraints by composing annotations
A composed constraint is an annotation that is itself annotated with existing constraints, with @Constraint(validatedBy = {}) and no validator class. @ReportAsSingleViolation makes it report one message instead of one per part.
A mobile number rule needs a pattern and a length. @IndianMobile packs @Pattern and @Size under one name. The example shows it and checks two wrong numbers.
Example 2 · IndianMobile.java, IndianMobileDemo.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/custom/IndianMobile.javapackage com.shoplite.lab.custom;
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;
import jakarta.validation.Constraint;import jakarta.validation.Payload;import jakarta.validation.ReportAsSingleViolation;import jakarta.validation.constraints.Pattern;import jakarta.validation.constraints.Size;
@Pattern(regexp = "^[6-9][0-9]*$")@Size(min = 10, max = 10)@ReportAsSingleViolation // one message for the whole check, not one per part@Constraint(validatedBy = {})@Documented@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE})@Retention(RetentionPolicy.RUNTIME)public @interface IndianMobile {
String message() default "must be 10 digits starting with 6-9";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};}
// src/main/java/com/shoplite/lab/custom/IndianMobileDemo.javapackage com.shoplite.lab.custom;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;
record NewCustomerForm(@IndianMobile String phone) {}
public class IndianMobileDemo {
public static void main(String[] args) { try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { Validator validator = factory.getValidator();
for (String phone : new String[] {"9876543210", "98765", "5876543210", "98765-43210", null}) { String shown = phone == null ? "null" : "\"" + phone + "\""; var problems = validator.validate(new NewCustomerForm(phone)); System.out.printf("%-14s %d problem(s)", shown, problems.size()); for (ConstraintViolation<NewCustomerForm> problem : problems) { System.out.print(": " + problem.getMessage()); } System.out.println(); } } }}11:04:52.414 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final "9876543210" 0 problem(s) "98765" 1 problem(s): must be 10 digits starting with 6-9 "5876543210" 1 problem(s): must be 10 digits starting with 6-9 "98765-43210" 1 problem(s): must be 10 digits starting with 6-9 null 0 problem(s)
What this code does
- There is no validator class:
@Patternand@Sizedo the work, and@Constraint(validatedBy = {})marks the annotation as a constraint. "98765"matches the pattern but is too short,"5876543210"has the right length but the wrong first digit; both get the same single message thanks to@ReportAsSingleViolation.nullis valid, because phone is optional in ShopLite.
Without @ReportAsSingleViolation, every broken part reports its own message, so "98765" could get both a pattern message and a size message. With it, the client gets one clear message, "must be 10 digits starting with 6-9", whatever part failed.
Compose when built-ins can express the rule (formats, lengths, ranges); write a ConstraintValidator when you need code: a list lookup, a checksum, or a rule about two fields. ShopLite uses both: @IndianMobile and @Pincode are composed, @Sku has a validator.
A class-level validator for cross-field rules: sale price below price
A class-level constraint is placed on a class or record (@Target(ElementType.TYPE)), so its validator receives the whole object and can compare fields, for example the sale price against the price.
A rule like "the sale price must be lower than the price" needs two fields at once, and a field constraint sees only its own value. The example puts the check on the whole record.
Example 3 · SalePriceBelowPrice.java, SalePriceBelowPriceValidator.java, FestivalOfferRequest.java, FestivalOfferDemo.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/custom/SalePriceBelowPrice.javapackage com.shoplite.lab.custom;
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;
import jakarta.validation.Constraint;import jakarta.validation.Payload;
@Documented@Constraint(validatedBy = SalePriceBelowPriceValidator.class)@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface SalePriceBelowPrice {
String message() default "must be lower than price";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};}
// src/main/java/com/shoplite/lab/custom/SalePriceBelowPriceValidator.javapackage com.shoplite.lab.custom;
import jakarta.validation.ConstraintValidator;import jakarta.validation.ConstraintValidatorContext;
public class SalePriceBelowPriceValidator implements ConstraintValidator<SalePriceBelowPrice, FestivalOfferRequest> {
@Override public boolean isValid(FestivalOfferRequest offer, ConstraintValidatorContext context) { if (offer == null || offer.price() == null || offer.salePrice() == null) { return true; } if (offer.salePrice().compareTo(offer.price()) < 0) { return true; } context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addPropertyNode("salePrice") .addConstraintViolation(); return false; }}
// src/main/java/com/shoplite/lab/custom/FestivalOfferRequest.javapackage com.shoplite.lab.custom;
import java.math.BigDecimal;
import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.NotNull;
@SalePriceBelowPricepublic record FestivalOfferRequest( @NotNull(message = "is required") @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0") BigDecimal price,
@NotNull(message = "is required") @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0") BigDecimal salePrice) {}
package com.shoplite.lab.custom;
import java.math.BigDecimal;import java.util.Comparator;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;
public class FestivalOfferDemo {
public static void main(String[] args) { try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { Validator validator = factory.getValidator();
check(validator, new FestivalOfferRequest(new BigDecimal("1299.00"), new BigDecimal("999.00"))); check(validator, new FestivalOfferRequest(new BigDecimal("1299.00"), new BigDecimal("1499.00"))); check(validator, new FestivalOfferRequest(new BigDecimal("1299.00"), new BigDecimal("1299.00"))); check(validator, new FestivalOfferRequest(null, new BigDecimal("-1.00"))); } }
static void check(Validator validator, FestivalOfferRequest offer) { var problems = validator.validate(offer); System.out.println("price " + offer.price() + ", sale " + offer.salePrice() + " -> " + (problems.isEmpty() ? "valid" : "invalid")); problems.stream() .sorted(Comparator.comparing((ConstraintViolation<FestivalOfferRequest> v) -> v.getPropertyPath().toString())) .forEach(v -> System.out.println(" " + v.getPropertyPath() + " " + v.getMessage())); }}11:04:54.431 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final price 1299.00, sale 999.00 -> valid price 1299.00, sale 1499.00 -> invalid salePrice must be lower than price price 1299.00, sale 1299.00 -> invalid salePrice must be lower than price price null, sale -1.00 -> invalid price is required salePrice must be greater than 0
What this code does
ConstraintValidator<SalePriceBelowPrice, FestivalOfferRequest>: the second type is the whole record, because the annotation sits on the record.- A sale price equal to the price is rejected too (
compareTo(...) < 0is required), and the error appears assalePrice, not on the object. - In the last case the price is missing, so the class-level check steps aside and only the field constraints report. The sale offer is a lab example; the ShopLite contract has no sale price.
By default the error is reported on the object itself, with an empty field path, and clients cannot tell which input to fix. Inside isValid, the context calls attach it to salePrice instead.
Return true when one of the values is missing: @NotNull on the fields reports that, and the client should not get a confusing "must be lower than price" for a price that was never sent.
Order of execution
Report the error on salePrice
Put the context calls inside isValid in the order they must run.
Validation groups for create vs update, and when to use separate DTOs
A validation group is a marker interface, such as OnReplace, that labels some constraints: @NotNull(groups = OnReplace.class). You choose which groups to check; constraints without groups belong to Default.
A create request may leave stock out, but a replace request must send it. The example uses groups so one form serves both, then picks the group in a controller.
Example 4 · ProductForm.java, GroupsDemo.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
// src/main/java/com/shoplite/lab/custom/ProductForm.javapackage com.shoplite.lab.custom;
import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.groups.Default;
public record ProductForm( @NotNull(message = "is required") @Sku String sku,
@NotNull(groups = ProductForm.OnReplace.class, message = "is required when replacing") @PositiveOrZero(message = "must be 0 or more") Integer stock,
@NotNull(groups = ProductForm.OnReplace.class, message = "is required when replacing") Boolean isActive) {
public interface OnReplace extends Default { }}
// src/main/java/com/shoplite/lab/custom/GroupsDemo.javapackage com.shoplite.lab.custom;
import java.util.Comparator;import java.util.Set;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;
public class GroupsDemo {
public static void main(String[] args) { try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { Validator validator = factory.getValidator(); ProductForm form = new ProductForm("ACC-KB100", null, null); // no stock, no isActive
print("Create (Default group)", validator.validate(form)); print("Replace (OnReplace group)", validator.validate(form, ProductForm.OnReplace.class));
ProductForm badSku = new ProductForm("kb 1", 5, true); print("Replace with a bad SKU", validator.validate(badSku, ProductForm.OnReplace.class)); } }
static void print(String title, Set<ConstraintViolation<ProductForm>> problems) { System.out.println(title + ": " + problems.size() + " problem(s)"); problems.stream() .sorted(Comparator.comparing((ConstraintViolation<ProductForm> v) -> v.getPropertyPath().toString())) .forEach(v -> System.out.println(" " + v.getPropertyPath() + " " + v.getMessage())); }}11:04:56.397 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final Create (Default group): 0 problem(s) Replace (OnReplace group): 2 problem(s) isActive is required when replacing stock is required when replacing Replace with a bad SKU: 1 problem(s) sku must be 3-20 characters: A-Z, 0-9 or -
What this code does
- The same form passes the default checks (create) but fails
OnReplace, which requiresstockandisActive. - Because
OnReplace extends Default, the replace check also runs the default rules, so the bad SKU is still caught.
Example 5 · ProductFormController.java: choosing the group in a controller
Runs in: the validation-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.custom;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/lab/forms")public class ProductFormController {
@PostMapping public String create(@Valid @RequestBody ProductForm form) { // Default group return "create OK: " + form; }
@PutMapping("/{id}") public String replace(@PathVariable long id, @Validated(ProductForm.OnReplace.class) @RequestBody ProductForm form) { return "replace OK: " + form; }}$ curl -i -X POST http://localhost:8080/lab/forms -H "Content-Type: application/json" -d '{"sku": "ACC-KB100"}'
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
create OK: ProductForm[sku=ACC-KB100, stock=null, isActive=null]
$ curl -i -X PUT http://localhost:8080/lab/forms/16 -H "Content-Type: application/json" -d '{"sku": "ACC-KB100"}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-10-16T06:24:49.771Z","status":400,"error":"Bad Request","path":"/lab/forms/16"}
$ curl -i -X PUT http://localhost:8080/lab/forms/16 -H "Content-Type: application/json" -d '{"sku": "ACC-KB100", "stock": 30, "isActive": true}'
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
replace OK: ProductForm[sku=ACC-KB100, stock=30, isActive=true]
Server console (shortened):
2026-10-16T11:54:49.722+05:30 WARN 29684 --- [validation-lab] [io-18614-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed ... [Field error in object 'productForm' on field 'isActive': rejected value [null]; ... default message [isActive]] [Field error in object 'productForm' on field 'stock': rejected value [null]; ... default message [is required when replacing]]What this code does
@Validchecks theDefaultgroup;@Validated(ProductForm.OnReplace.class)(Spring's annotation, with a group) checksOnReplace, here on the PUT only.- The same JSON without
stockandisActivepasses POST and fails PUT. Compare this with ShopLite's separateCreateProductRequestandReplaceProductRequest, where each record simply shows its own rules.
Check a group with validator.validate(form, OnReplace.class) in code, or @Validated(OnReplace.class) @RequestBody in a controller. Making OnReplace extends Default checks both. Groups let one DTO serve POST and PUT, but every reader must work out which rules apply to which endpoint, and a forgotten group silently skips rules.
ShopLite uses separate DTOs instead: CreateProductRequest, ReplaceProductRequest and PatchProductRequest. Each record shows exactly what its endpoint accepts, and the duplication is small because @Sku and friends hold the shared rules. Keep groups for the rare case of one big form with small differences.
Predict the output
Which groups run?
Read the record and the call, then pick the number of violations.
Round 1 of 3
Unit testing a validator with Validator directly
A validator unit test builds a Validator with Validation.buildDefaultValidatorFactory() and checks objects without starting Spring, so it runs in about a second and needs no web server.
Custom rules deserve tests. The test class below runs 11 checks on the SKU and sale-price rules without starting Spring.
Example 6 · src/test/java/com/shoplite/lab/custom/CustomConstraintsTest.java
Runs in: the validation-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.custom;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;import java.util.List;import java.util.Set;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;
import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;
class CustomConstraintsTest {
private static ValidatorFactory factory; private static Validator validator;
@BeforeAll static void createValidator() { factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); }
@AfterAll static void closeFactory() { factory.close(); }
@ParameterizedTest @ValueSource(strings = {"MOB-RN13", "ACC-KB100", "BK-123"}) void acceptsGoodSkus(String sku) { assertThat(validator.validate(new NewProductForm(sku))).isEmpty(); }
@ParameterizedTest @ValueSource(strings = {"", "kb 1", "AB", "mob-rn13", "ABCDEFGHIJKLMNOPQRSTU"}) void rejectsBadSkus(String sku) { assertThat(messages(validator.validate(new NewProductForm(sku)))) .containsExactly("must be 3-20 characters: A-Z, 0-9 or -"); }
@Test void missingSkuGetsOnlyTheRequiredMessage() { assertThat(messages(validator.validate(new NewProductForm(null)))) .containsExactly("is required"); }
@Test void salePriceEqualToPriceIsRejectedOnTheSalePriceField() { var offer = new FestivalOfferRequest(new BigDecimal("1299.00"), new BigDecimal("1299.00")); var problems = validator.validate(offer);
assertThat(problems).hasSize(1); ConstraintViolation<FestivalOfferRequest> problem = problems.iterator().next(); assertThat(problem.getPropertyPath().toString()).isEqualTo("salePrice"); assertThat(problem.getMessage()).isEqualTo("must be lower than price"); }
@Test void lowerSalePriceIsValid() { var offer = new FestivalOfferRequest(new BigDecimal("1299.00"), new BigDecimal("999.00")); assertThat(validator.validate(offer)).isEmpty(); }
private static <T> List<String> messages(Set<ConstraintViolation<T>> problems) { return problems.stream().map(ConstraintViolation::getMessage).sorted().toList(); }}$ mvn test -Dtest=CustomConstraintsTest ... [INFO] Running com.shoplite.lab.custom.CustomConstraintsTest [INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.750 s -- in com.shoplite.lab.custom.CustomConstraintsTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
- One
ValidatorFactoryfor the class (@BeforeAll), closed in@AfterAll. No Spring context starts, so the 11 checks run in under two seconds. @ParameterizedTestwith@ValueSourceruns one test per SKU: 3 good and 5 bad ones, including""and a 21-character SKU.- The sale price test asserts both the property path and the message, the two things a client sees.
A ConstraintValidator with no dependencies can even be tested by calling new SkuValidator().isValid(value, null). Test the edges, not only the happy path: the shortest and longest allowed values, one character too many, lowercase letters, an empty string, and null. Assert the exact message and the property path (salePrice), because the client depends on both.
These tests catch the bugs that reach production most often: a validator that returns the wrong result for null, a message typo, or an error reported on the wrong field.
Next step
Check your understanding
12 quick questions