Careeroza
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) | Checks | Null allowed? |
|---|---|---|
@NotNull | value is not null | no |
@NotBlank | string is not null and not only spaces | no |
@NotEmpty | string/collection not null and not empty | no |
@Size(min, max) | length of string / size of collection | yes |
@Min / @Max | whole number range | yes |
@Positive / @PositiveOrZero | number > 0 / >= 0 | yes |
@DecimalMin("0.01") / @Digits(integer, fraction) | decimal limits and precision | yes |
@Email | looks like an email address | yes |
@Pattern(regexp) | matches a regular expression | yes |
@Past / @Future | date before / after now | yes |
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) {}