0 day streak
java / beginner
Snippet

Validating Request Data Transfer Objects

Validating input models ensures incoming payloads meet required structural and data-type constraints before processing. Bean Validation annotations like @NotBlank and @Min define constraints directly on class fields, encapsulating validation rules within the object definition.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
public class CreateUserRequest {
@NotBlank(message = "Username is mandatory")
private String username;
@Min(value = 18, message = "Age must be at least 18")
private int age;
public String getUsername() { return username; }
public int getAge() { return age; }
}
spring
Breakdown
1
@NotBlank(message = "Username is mandatory")
Ensures the username field is not null and contains at least one non-whitespace character.
2
@Min(value = 18, message = "Age must be at least 18")
Constrains the integer age field to have a numerical value of 18 or greater.
3
public String getUsername() { return username; }
Encapsulated getter method providing read access to the validated username field.