0
0
Spring Bootframework~5 mins

@Size for length constraints in Spring Boot

Choose your learning style9 modes available
Introduction

The @Size annotation helps check if a text or collection has the right length. It stops errors by making sure data is not too short or too long.

When you want to make sure a username is at least 3 characters and no more than 15 characters.
When you need to check that a password has a minimum length for security.
When validating a list of items to ensure it has a certain number of elements.
When you want to limit the length of a comment or description in a form.
When you want to enforce size rules on arrays or collections in your data model.
Syntax
Spring Boot
@Size(min = X, max = Y, message = "custom error message")
You can use min to set the minimum length and max for the maximum length.
The message is optional and shows a friendly error if the size is wrong.
Examples
This means the username must be between 3 and 10 characters long.
Spring Boot
@Size(min = 3, max = 10)
private String username;
The description can be empty or up to 50 characters. If longer, it shows the custom message.
Spring Boot
@Size(max = 50, message = "Description too long")
private String description;
The list of tags must have at least one item.
Spring Boot
@Size(min = 1)
private List<String> tags;
Sample Program

This program creates a user with a username that is too short. It uses @Size to check the username length. The validator prints the error message if the username is not between 3 and 10 characters.

Spring Boot
import jakarta.validation.constraints.Size;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.ConstraintViolation;
import java.util.Set;

public class User {
    @Size(min = 3, max = 10, message = "Username must be 3 to 10 characters")
    private String username;

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

    public static void main(String[] args) {
        User user = new User("Jo"); // too short

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<User>> violations = validator.validate(user);

        if (violations.isEmpty()) {
            System.out.println("User is valid");
        } else {
            for (ConstraintViolation<User> violation : violations) {
                System.out.println(violation.getMessage());
            }
        }
    }
}
OutputSuccess
Important Notes

The @Size annotation works on strings, collections, arrays, and maps.

Make sure to add a validation framework like Hibernate Validator to your project to use @Size.

Use clear messages to help users fix their input easily.

Summary

@Size checks if text or collections have the right length.

Use min and max to set limits.

It helps catch input errors early and improve user experience.