Bean Validation Annotations

Add the Starter

Never trust client input. Spring Boot uses Jakarta Bean Validation (implemented by Hibernate Validator). It is a separate starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Common Constraints

Annotation (jakarta.validation.constraints)ChecksNull allowed?
@NotNullvalue is not nullno
@NotBlankstring is not null and not only spacesno
@NotEmptystring/collection not null and not emptyno
@Size(min, max)length of string / size of collectionyes
@Min / @Maxwhole number rangeyes
@Positive / @PositiveOrZeronumber > 0 / >= 0yes
@DecimalMin("0.01") / @Digits(integer, fraction)decimal limits and precisionyes
@Emaillooks like an email addressyes
@Pattern(regexp)matches a regular expressionyes
@Past / @Futuredate before / after nowyes

Note: Most constraints treat null as valid. Combine them with @NotNull when the field is required: @NotNull @Positive BigDecimal price.

Annotating the ShopEase DTO

import jakarta.validation.constraints.*;
import java.math.BigDecimal;

public record CreateProductRequest(
        @NotBlank @Size(max = 120)
        String name,

        @Size(max = 2000)
        String description,

        @NotNull @DecimalMin("0.01") @Digits(integer = 8, fraction = 2)
        BigDecimal price,

        @PositiveOrZero
        int stock,

        @NotBlank(message = "category is required")
        String category) {}