0
0
Spring Bootframework~5 mins

Validation groups in Spring Boot

Choose your learning style9 modes available
Introduction

Validation groups help you apply different validation rules to the same data depending on the situation. This way, you can reuse your validation logic but change what is checked.

When you want to validate user input differently for creating and updating data.
When you have a form with optional sections that require different validations.
When you want to apply stricter checks in some cases but relaxed checks in others.
When you want to reuse the same object but validate only some fields in certain flows.
Syntax
Spring Boot
public interface GroupName {}

@Validated(GroupName.class)
public class YourClass {
    @NotNull(groups = GroupName.class)
    private String field;
}

Define empty interfaces to represent groups.

Use groups attribute in validation annotations to assign them to groups.

Examples
Two groups are defined: CreateGroup and UpdateGroup. The username is required only when creating, but email is required in both cases.
Spring Boot
public interface CreateGroup {}
public interface UpdateGroup {}

public class User {
    @NotNull(groups = CreateGroup.class)
    private String username;

    @NotNull(groups = {CreateGroup.class, UpdateGroup.class})
    private String email;
}
This method validates the user object only for the CreateGroup rules.
Spring Boot
@Validated(CreateGroup.class)
public void createUser(@Valid User user) {
    // validation applies only for CreateGroup
}
Sample Program

This example shows a User class with two validation groups: CreateGroup and UpdateGroup. The username is required only when creating a user. The email is required in both create and update. The main method validates two users with different groups and prints how many violations each has.

Spring Boot
import jakarta.validation.constraints.*;
import jakarta.validation.*;
import org.springframework.validation.annotation.Validated;
import java.util.Set;

public class ValidationGroupsExample {

    public interface CreateGroup {}
    public interface UpdateGroup {}

    public static class User {
        @NotNull(groups = CreateGroup.class)
        private String username;

        @NotNull(groups = {CreateGroup.class, UpdateGroup.class})
        private String email;

        public User(String username, String email) {
            this.username = username;
            this.email = email;
        }

        // getters and setters omitted for brevity
    }

    public static void main(String[] args) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        User userForCreate = new User(null, "user@example.com");
        User userForUpdate = new User(null, null);

        Set<ConstraintViolation<User>> createViolations = validator.validate(userForCreate, CreateGroup.class);
        Set<ConstraintViolation<User>> updateViolations = validator.validate(userForUpdate, UpdateGroup.class);

        System.out.println("Create group violations: " + createViolations.size());
        System.out.println("Update group violations: " + updateViolations.size());
    }
}
OutputSuccess
Important Notes

Validation groups let you control which validations run in different situations.

Always define groups as empty interfaces for clarity.

Use the groups attribute on validation annotations to assign them to groups.

Summary

Validation groups help apply different validation rules to the same object.

Define groups as empty interfaces and assign validations to them.

Use the validator with a specific group to run only those validations.