java / beginner
Snippet
Field Validation with Constraints
Spring supports Bean Validation (JSR-303). By adding annotations like @NotBlank or @Min to your class fields, you can enforce rules on incoming data to ensure it meets your requirements.
snippet.java
1
2
3
4
5
6
7
public class UserRequest {@NotBlank(message = "Username is required")private String username;@Min(value = 18, message = "Must be at least 18")private int age;}
spring
Breakdown
1
@NotBlank
Ensures that the string field is not null and has a trimmed length greater than zero.
2
@Min(value = 18)
Validates that the numeric field has a value no less than the specified minimum.