Bean Validation

Bean Validation in Spring Boot is a framework for validating the properties of a JavaBean using annotations. It leverages the Java Bean Validation API (JSR 380) and Hibernate Validator to perform validation. It

  • Ensure data integrity by validating user input at the application layer.

  • Reduce boilerplate validation logic in your code by relying on declarative annotations.

  • Integrates seamlessly with Spring Boot's controller and service layers.

  • To use bean validation, use starter

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

Common Bean Validation Annotations

Annotation

Description

@NotNull

Ensures the property is not null.

@NotEmpty

Ensures the property is not null or empty (only for Strings and collections).

@NotBlank

Ensures the property is not null or blank (for Strings).

@Size

Restricts the size of a String, collection, array, or map.

@Min / @Max

Sets minimum and maximum values for numeric fields.

@Email

Validates an email format.

@Pattern

Validates against a regular expression.

@Positive / @Negative

Ensures the property is positive or negative.

@Valid

Triggers validation for nested objects.

@Past / @Future

Ensures the property is a date in the past or future.

To validate bean object we can use @Valid in controller or service layer

How to handle exceptions when validation fails?

How to validate nested objects?

Use @Valid on nested objects to trigger validation:

How to do groups and conditional validation?

To do group or conditional validation, we can use groups attribute and @Validated .

How to do custom validation of beans?

To do custom validation of beans we can use validation factory and the validator class

How to create own custom validation constraints?

To create our own custom validation constraints we need to create a custom annotation a validator class by extending ConstraintValidator.

Below there is an example of custom constraint for validate file.

A custom validator to validate it.

Use of this custom constraint

Handle Exceptions Using Problem Detail

Last updated