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.
@Size for length constraints in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
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
Spring Boot
@Size(min = 3, max = 10) private String username;
Spring Boot
@Size(max = 50, message = "Description too long") private String description;
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()); } } } }
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.
Practice
1. What does the
@Size annotation do in Spring Boot validation?easy
Solution
Step 1: Understand the purpose of @Size
@Size is used to validate the length of strings or collections, not numeric ranges or null checks.Step 2: Identify what @Size checks
It usesminandmaxto set length limits on text or collections.Final Answer:
It checks if a string or collection length is within specified min and max limits. -> Option CQuick Check:
@Size validates length = C [OK]
Hint: Remember @Size controls length, not value or null checks [OK]
Common Mistakes:
- Confusing @Size with @Min/@Max for numbers
- Thinking @Size checks null values
- Assuming @Size validates patterns
2. Which of the following is the correct way to use
@Size to require a string between 5 and 10 characters?easy
Solution
Step 1: Recall correct @Size syntax
The correct attributes areminandmaxfor length limits.Step 2: Check each option
Only @Size(min=5, max=10) uses valid attribute names and syntax.Final Answer:
@Size(min=5, max=10) -> Option AQuick Check:
Use min and max attributes = A [OK]
Hint: Use min and max, not length or range attributes [OK]
Common Mistakes:
- Using invalid attribute names like length or range
- Trying to pass a range as a string
- Confusing @Size with other annotations
3. Given this code snippet:
Which input value will pass validation?
@Size(min=3, max=6) private String code;
Which input value will pass validation?
medium
Solution
Step 1: Understand the length limits
The string must have length between 3 and 6 characters inclusive.Step 2: Check each input length
"ab" length is 2 (too short), "abcdefg" length is 7 (too long), "abcde" length is 5 (valid), "" length is 0 (too short).Final Answer:
"abcde" -> Option BQuick Check:
Length between 3 and 6 = "abcde" [OK]
Hint: Count characters; must be between min and max [OK]
Common Mistakes:
- Ignoring inclusive limits
- Counting characters incorrectly
- Assuming empty string passes
4. Identify the error in this code snippet:
@Size(min=2, max=5) private int number;
medium
Solution
Step 1: Check @Size target types
@Size works on strings, collections, arrays, but not on primitive types like int.Step 2: Analyze the code
The field is an int, so @Size is invalid here and will cause an error.Final Answer:
@Size cannot be applied to primitive types like int. -> Option AQuick Check:
@Size only for strings/collections = D [OK]
Hint: Use @Size only on strings or collections, not primitives [OK]
Common Mistakes:
- Applying @Size to numbers
- Confusing @Size with @Min/@Max for numbers
- Ignoring type compatibility
5. You want to validate a list of usernames where each username must be between 4 and 12 characters. Which is the correct way to apply
@Size in your Spring Boot model?hard
Solution
Step 1: Understand @Size on collections vs elements
@Size on a collection checks the collection size, not each element's length.Step 2: Apply @Size to elements inside the collection
To validate each username's length, use @Size on the generic type parameter or element level.Step 3: Analyze options
private List<@Size(min=4, max=12) String> usernames; correctly applies @Size to each String element in the List.Final Answer:
private List<@Size(min=4, max=12) String> usernames; -> Option DQuick Check:
Use @Size on elements for per-item length = D [OK]
Hint: Put @Size on list elements, not just the list itself [OK]
Common Mistakes:
- Applying @Size only on the list, not elements
- Using invalid syntax for generic annotations
- Confusing collection size with element length
