Skip to lesson

Bean Validation annotations

A shop that accepts a product with a blank name or a negative price ends up with bad data in its database. Rules written once as annotations stop that at the door.

Adding spring-boot-starter-validation and the jakarta.validation package

Bean Validation is the Java standard (jakarta.validation) for writing input rules as annotations on fields, such as @NotBlank or @Email. Hibernate Validator, which spring-boot-starter-validation adds, runs the checks.

Before a product reaches the database, a rule must reject a blank name. The command below lists the libraries that the validation starter brings into a ShopLite project.

Terminal
mvn dependency:tree -Dincludes=org.hibernate.validator,jakarta.validation
Output
[INFO] com.shoplite:validation-lab:jar:0.0.1-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-validation:jar:4.1.1:compile
[INFO]    \- org.springframework.boot:spring-boot-validation:jar:4.1.1:compile
[INFO]       \- org.hibernate.validator:hibernate-validator:jar:9.1.3.Final:compile
[INFO]          \- jakarta.validation:jakarta.validation-api:jar:3.1.1:compile

Example 1 · src/main/java/com/shoplite/lab/annotations/FirstValidationDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

FirstValidationDemo.javaJava
package com.shoplite.lab.annotations;
import java.util.Set;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.NotBlank;
record NewCategoryRequest(@NotBlank String name) {}
public class FirstValidationDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();
            check(validator, new NewCategoryRequest("Mobiles"));            check(validator, new NewCategoryRequest("   "));        }    }
    static void check(Validator validator, NewCategoryRequest request) {        Set<ConstraintViolation<NewCategoryRequest>> problems = validator.validate(request);        System.out.println(request + " -> " + problems.size() + " problem(s)");        for (ConstraintViolation<NewCategoryRequest> problem : problems) {            System.out.println("  " + problem.getPropertyPath() + ": " + problem.getMessage());        }    }}
Sample output
11:04:40.322 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
NewCategoryRequest[name=Mobiles] -> 0 problem(s)
NewCategoryRequest[name=   ] -> 1 problem(s)
  name: must not be blank

What this code does

  • Validation.buildDefaultValidatorFactory() finds Hibernate Validator on the classpath. The factory is AutoCloseable, so try-with-resources closes it; getValidator() gives the object that checks.
  • validate returns a Set of violations: empty for "Mobiles", one for three spaces. getPropertyPath() names the field and getMessage() gives "must not be blank".
  • The first line is Hibernate Validator's start-up log; its time differs on your computer. Run the class from your IDE like any main method: it uses the starter's libraries but does not start Spring.

The starter adds the Bean Validation API (package jakarta.validation, version 3.1 in Spring Boot 4.1) and Hibernate Validator 9. Without them, every method starts with hand-written if (name == null || name.isBlank()) checks, copied a little differently each time, and one missed check lets bad data in.

You put constraint annotations on fields or record components. A Validator then returns one ConstraintViolation per broken rule, with the field path and a message; an empty set means the object is valid. If the starter is missing, the project fails with package jakarta.validation.constraints does not exist, and old javax.validation imports do not work with Spring Boot 3 or 4.

Add the starter to pom.xml with groupId org.springframework.boot and artifactId spring-boot-starter-validation, without a version: the Spring Boot parent picks versions that work together. The command above lists what it brought in.

@NotNull vs @NotEmpty vs @NotBlank

@NotNull rejects only null. @NotEmpty also rejects an empty String, list, map or array. @NotBlank, for text only, also rejects text made of spaces.

Users and apps send three kinds of "nothing": null, an empty string and spaces. The program below sends the same four inputs through all three annotations.

Example 2 · src/main/java/com/shoplite/lab/annotations/BlankChecksDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

BlankChecksDemo.javaJava
package com.shoplite.lab.annotations;
import java.util.Set;import java.util.stream.Collectors;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotEmpty;import jakarta.validation.constraints.NotNull;
// The same text goes into all three fields, so we can compare the annotationsrecord NameChecks(@NotNull String notNull,                  @NotEmpty String notEmpty,                  @NotBlank String notBlank) {}
public class BlankChecksDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();
            System.out.println("input     @NotNull  @NotEmpty  @NotBlank");            String[] inputs = {null, "", "   ", "Asha"};            for (String input : inputs) {                Set<String> failed = validator.validate(new NameChecks(input, input, input))                        .stream()                        .map(v -> v.getPropertyPath().toString())                        .collect(Collectors.toSet());
                String shown = input == null ? "null" : "\"" + input + "\"";                System.out.printf("%-9s %-9s %-10s %s%n", shown,                        result(failed, "notNull"), result(failed, "notEmpty"), result(failed, "notBlank"));            }        }    }
    static String result(Set<String> failedFields, String field) {        return failedFields.contains(field) ? "fail" : "pass";    }}
Sample output
11:04:42.126 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
input     @NotNull  @NotEmpty  @NotBlank
null      fail      fail       fail
""        pass      fail       fail
"   "     pass      pass       fail
"Asha"    pass      pass       pass

What this code does

  • The same value goes into all three fields, so each row compares the three annotations on one input.
  • "" passes only @NotNull; three spaces pass @NotNull and @NotEmpty and fail only @NotBlank. For required text, @NotBlank is the one that matches what a user means by "empty".

A sign-up form with three spaces in the name passes @NotEmpty and ends up as a customer with a blank name on every invoice.

Pick by type: @NotBlank for required text, @NotEmpty for a required list, @NotNull for numbers, dates, booleans and nested objects. @NotBlank on an Integer is a mistake that only shows up at run time, as the next section shows.

Predict the output

How many violations?

Read each record and the value, then pick the number of violations.

Round 1 of 3

record Customer(@NotEmpty String name) { }
validator.validate(new Customer(" ")).size()

Numbers and sizes: @Size, @Min, @Max, @Positive, @DecimalMin and @Digits

@DecimalMin sets the smallest allowed BigDecimal; with inclusive = false the value must be more than it. @Digits(integer, fraction) limits the digits before and after the point. Together they validate money.

A product price must be above zero and fit a DECIMAL(10,2) column, and stock cannot be negative. The first program checks both; the second puts a constraint on the wrong type.

Example 3 · src/main/java/com/shoplite/lab/annotations/NumberChecksDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

NumberChecksDemo.javaJava
package com.shoplite.lab.annotations;
import java.math.BigDecimal;import java.util.Comparator;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Digits;import jakarta.validation.constraints.Max;import jakarta.validation.constraints.Min;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.constraints.Size;
record ProductForm(        @NotBlank @Size(min = 2, max = 120) String name,        @NotNull @DecimalMin(value = "0.00", inclusive = false) @Digits(integer = 8, fraction = 2) BigDecimal price,        @PositiveOrZero Integer stock) {}
record CartLine(@NotNull @Min(1) @Max(10) Integer quantity) {}
public class NumberChecksDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();
            check(validator, new ProductForm("Redmi Note 13 5G", new BigDecimal("17999.00"), 40));            check(validator, new ProductForm("K", new BigDecimal("0.00"), -1));            check(validator, new ProductForm("USB-C Cable", new BigDecimal("199.999"), null));            check(validator, new ProductForm("Gaming PC", new BigDecimal("123456789.00"), 5));            check(validator, new ProductForm("Pen", null, 10));            check(validator, new CartLine(0));            check(validator, new CartLine(11));            check(validator, new CartLine(2));        }    }
    static <T> void check(Validator validator, T form) {        System.out.println(form);        validator.validate(form).stream()                .sorted(Comparator.comparing((ConstraintViolation<T> v) -> v.getPropertyPath().toString())                        .thenComparing(ConstraintViolation::getMessage))                .forEach(v -> System.out.println("  " + v.getPropertyPath() + ": " + v.getMessage()));    }}
Sample output
11:04:43.677 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
ProductForm[name=Redmi Note 13 5G, price=17999.00, stock=40]
ProductForm[name=K, price=0.00, stock=-1]
  name: size must be between 2 and 120
  price: must be greater than 0.00
  stock: must be greater than or equal to 0
ProductForm[name=USB-C Cable, price=199.999, stock=null]
  price: numeric value out of bounds (<8 digits>.<2 digits> expected)
ProductForm[name=Gaming PC, price=123456789.00, stock=5]
  price: numeric value out of bounds (<8 digits>.<2 digits> expected)
ProductForm[name=Pen, price=null, stock=10]
  price: must not be null
CartLine[quantity=0]
  quantity: must be greater than or equal to 1
CartLine[quantity=11]
  quantity: must be less than or equal to 10
CartLine[quantity=2]

What this code does

  • @DecimalMin(value = "0.00", inclusive = false) rejects 0.00; @Digits(integer = 8, fraction = 2) rejects both 199.999 (3 decimals) and 123456789.00 (9 digits before the point).
  • stock=null passes @PositiveOrZero, because constraints other than the null checks skip null. price=null fails only because of @NotNull.
  • Violations come back in a Set with no fixed order, so the program sorts them by field to print the same lines on every run.

Example 4 · src/main/java/com/shoplite/lab/annotations/WrongTypeDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

WrongTypeDemo.javaJava
package com.shoplite.lab.annotations;
import jakarta.validation.UnexpectedTypeException;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.Size;
// Mistake: @Size is for text, collections and arrays, not for numbersrecord TicketRequest(@Size(min = 1, max = 6) Integer passengers) {}
public class WrongTypeDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();            try {                validator.validate(new TicketRequest(2));                System.out.println("valid");            } catch (UnexpectedTypeException e) {                System.out.println(e.getClass().getSimpleName());                System.out.println(e.getMessage());            }        }    }}
Sample output
11:04:45.445 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
UnexpectedTypeException
HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Size' validating type 'java.lang.Integer'. Check configuration for 'passengers'

What this code does

  • The code compiles: the compiler does not know which types @Size supports. The mistake appears only when the object is validated, as UnexpectedTypeException with code HV000030.
  • In a web app this would be a 500 error on every request to that endpoint. The fix for a number is @Min(1) @Max(6) instead of @Size.

@Size(min, max) limits the length of text or the number of items in a collection. @Min and @Max limit whole numbers; @Positive means greater than 0 and @PositiveOrZero means 0 or more. Two rules catch beginners. Every constraint except the null checks treats null as valid, so a required field also needs @NotNull. And each annotation works only on certain types: @Size on an Integer compiles, then fails at the first check with UnexpectedTypeException.

In an interview, "how do you validate a price?" has a clear answer: BigDecimal with @NotNull, @DecimalMin (exclusive) and @Digits, never a double.

Fix the error

Fix the wrong type

Read the real error, then pick the line that fixes it.

Round 1 of 2

The number of passengers must be between 1 and 6.

record TicketRequest(
@Size(min = 1, max = 6) Integer passengers) {
}

Error

jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.Size' validating type 'java.lang.Integer'. Check configuration for 'passengers'

@Email and @Pattern: phone numbers and SKUs

@Pattern(regexp = "...") checks that the whole text matches a regular expression. @Email checks that text looks like an e-mail address. Both treat null as valid.

A ShopLite phone is a 10-digit mobile number starting with 6 to 9, and a SKU is capitals, digits and -. The program below checks both with @Pattern, and an address with @Email.

Example 5 · src/main/java/com/shoplite/lab/annotations/PatternChecksDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

PatternChecksDemo.javaJava
package com.shoplite.lab.annotations;
import java.util.Set;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.Email;import jakarta.validation.constraints.Pattern;
record EmailField(@Email String email) {}
record PhoneField(@Pattern(regexp = "^[6-9][0-9]{9}$") String phone) {}
record SkuField(@Pattern(regexp = "^[A-Z0-9-]{3,20}$") String sku) {}
public class PatternChecksDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();
            for (String email : new String[] {"asha.rao@example.com", "asha.rao", "asha@localhost", ""}) {                show("email", email, validator.validate(new EmailField(email)));            }            for (String phone : new String[] {"9876543210", "98765 43210", "+919876543210", "5876543210", null}) {                show("phone", phone, validator.validate(new PhoneField(phone)));            }            for (String sku : new String[] {"MOB-RN13", "mob-rn13", "MOB RN13"}) {                show("sku", sku, validator.validate(new SkuField(sku)));            }            // The message of a failed @Pattern shows the regular expression itself            System.out.println(validator.validate(new PhoneField("12345")).iterator().next().getMessage());        }    }
    static <T> void show(String field, String value, Set<ConstraintViolation<T>> problems) {        String shown = value == null ? "null" : "\"" + value + "\"";        System.out.printf("%-6s %-24s %s%n", field, shown, problems.isEmpty() ? "valid" : "invalid");    }}
Sample output
11:04:47.115 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
email  "asha.rao@example.com"   valid
email  "asha.rao"               invalid
email  "asha@localhost"         valid
email  ""                       valid
phone  "9876543210"             valid
phone  "98765 43210"            invalid
phone  "+919876543210"          invalid
phone  "5876543210"             invalid
phone  null                     valid
sku    "MOB-RN13"               valid
sku    "mob-rn13"               invalid
sku    "MOB RN13"               invalid
must match "^[6-9][0-9]{9}$"

What this code does

  • The phone pattern rejects spaces, a +91 prefix and numbers starting with 5; null is valid because the phone is optional in ShopLite.
  • @Email accepts asha@localhost and "". Pair it with @NotBlank for a required address.
  • The last line shows the default message of @Pattern: it prints the regular expression, which means nothing to a shop customer. The next section fixes that.

The phone pattern is [6-9][0-9]{9}; the SKU pattern is [A-Z0-9-]{3,20}. Because the whole value must match, start and end anchors are allowed but not needed. A required field also needs @NotNull or @NotBlank.

@Email is looser than most people expect: it accepts asha@localhost (no dot in the domain) and the empty string "". Treat it as a typo filter, not proof that the address works; only a confirmation e-mail proves that.

Writing clear messages with the message attribute

message is the attribute of every constraint that holds the text of the error. It can use placeholders such as {min}, {max} and {value}, which are filled in from the annotation.

The default text "size must be between 2 and 120" means little to a customer. The program below gives every rule a message that a user can act on.

Example 6 · src/main/java/com/shoplite/lab/annotations/MessagesDemo.java

Runs in: the validation-lab practice project (Spring Boot 4.1)

MessagesDemo.javaJava
package com.shoplite.lab.annotations;
import java.math.BigDecimal;import java.util.Comparator;
import jakarta.validation.ConstraintViolation;import jakarta.validation.Validation;import jakarta.validation.Validator;import jakarta.validation.ValidatorFactory;import jakarta.validation.constraints.DecimalMin;import jakarta.validation.constraints.Digits;import jakarta.validation.constraints.NotBlank;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Pattern;import jakarta.validation.constraints.Positive;import jakarta.validation.constraints.PositiveOrZero;import jakarta.validation.constraints.Size;
record CreateProductRequest(        @NotBlank(message = "is required")        @Pattern(regexp = "^[A-Z0-9-]{3,20}$", message = "must be 3-20 characters: A-Z, 0-9 or -")        String sku,
        @NotBlank(message = "is required")        @Size(min = 2, max = 120, message = "must be {min}-{max} characters")        String name,
        @NotNull(message = "is required")        @Positive(message = "must be a positive id")        Long categoryId,
        @NotNull(message = "is required")        @DecimalMin(value = "0.00", inclusive = false, message = "must be greater than 0")        @Digits(integer = 8, fraction = 2, message = "must have at most 8 digits before the point and 2 after")        BigDecimal price,
        @PositiveOrZero(message = "must be 0 or more")        Integer stock,
        Boolean isActive) {}
public class MessagesDemo {
    public static void main(String[] args) {        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {            Validator validator = factory.getValidator();
            check(validator, new CreateProductRequest("ACC-KB100", "Zebronics Wireless Keyboard",                    4L, new BigDecimal("999.00"), 30, null));            check(validator, new CreateProductRequest("kb 1", "K",                    4L, new BigDecimal("-5.00"), null, null));            check(validator, new CreateProductRequest("", null,                    null, new BigDecimal("12.345"), -3, true));        }    }
    static void check(Validator validator, CreateProductRequest request) {        var problems = validator.validate(request);        System.out.println(problems.isEmpty() ? "valid" : problems.size() + " invalid:");        problems.stream()                .sorted(Comparator.comparing((ConstraintViolation<CreateProductRequest> v) -> v.getPropertyPath().toString())                        .thenComparing(ConstraintViolation::getMessage))                .forEach(v -> System.out.println("  " + v.getPropertyPath() + " " + v.getMessage()));    }}
Sample output
11:04:49.008 [main] INFO org.hibernate.validator.internal.util.Version -- HV000001: Hibernate Validator 9.1.3.Final
valid
3 invalid:
  name must be 2-120 characters
  price must be greater than 0
  sku must be 3-20 characters: A-Z, 0-9 or -
6 invalid:
  categoryId is required
  name is required
  price must have at most 8 digits before the point and 2 after
  sku is required
  sku must be 3-20 characters: A-Z, 0-9 or -
  stock must be 0 or more

What this code does

  • These are the rules and messages of the ShopLite API contract for a new product. The second request is the contract's own example ("kb 1", "K", price -5.00) and gives exactly its three messages.
  • {min}-{max} became "2-120", taken from the @Size annotation.
  • The empty SKU breaks two rules, @NotBlank and @Pattern, so it gets two messages. The custom validator lesson replaces both with one @Sku annotation that reports one clear message.

The placeholders are filled in from the annotation, so each number is written only once. Write the message without the field name ("is required", not "sku is required"), because the error response shows the field next to it. Keep messages short and free of internal details.

Messages can also live in a ValidationMessages.properties file and be referenced as {product.sku.pattern}, which helps with translation. ShopLite keeps them next to the annotation so the rule and its message are read together.

Next step

Check your understanding

12 quick questions