The User Management System uses Jakarta Validation (formerly Bean Validation) to ensure data integrity. Validation annotations are applied to DTO fields and automatically enforced by Spring Boot.
The CreateUserDTO is used for user registration and has comprehensive validation.Location: src/main/java/dev/juanJe/userManagementSystem/dto/CreateUserDTO.java
@NotBlank(message = "Username obligatorio")@Size(min = 3, max = 20, message = "El username debe tener entre 3 y 20 caracteres")private String username;
"email": "invalid-email" // ✗ Missing @ and domain"email": "@example.com" // ✗ Missing local part"email": "user@" // ✗ Missing domain"email": "user [email protected]" // ✗ Contains space
Password Validation
@NotBlank(message = "Password obligatorio")@Size(min = 8, max = 16, message = "La password debe tener entre 8 y 16 caracteres")@Pattern( regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).*$", message = "La password debe tener al menos una numero, una letra minuscula y una letra mayuscula")private String password;
"password": "short1A" // ✗ Too short (< 8 chars)"password": "alllowercase123" // ✗ No uppercase letter"password": "ALLUPPERCASE123" // ✗ No lowercase letter"password": "NoDigitsHere" // ✗ No numeric digit"password": "VeryLongPasswordThatExceeds16Chars1" // ✗ Too long (> 16 chars)
Regex breakdown:
^ - Start of string
(?=.*[a-z]) - Positive lookahead for at least one lowercase letter
(?=.*[A-Z]) - Positive lookahead for at least one uppercase letter
(?=.*\d) - Positive lookahead for at least one digit
The LoginUserDTO is used for authentication and has minimal validation.Location: src/main/java/dev/juanJe/userManagementSystem/dto/LoginUserDTO.java
public class LoginUserDTO { private String email; private String password;}
Currently, LoginUserDTO does not have validation annotations. Authentication logic handles missing or invalid credentials through service-layer checks and returns appropriate ResponseStatusException errors.
Use multiple annotations for comprehensive validation:
@NotBlank(message = "Email is required")@Email(message = "Email must be valid")@Size(max = 100, message = "Email must not exceed 100 characters")private String email;
4
Use @Valid in controllers
Always add @Valid to request body parameters:
public ResponseEntity<?> createUser(@Valid @RequestBody CreateUserDTO dto) { // Validation happens automatically before this method executes}
@NotBlank(message = "Email obligatorio")@Email(message = "El email debe ser valido")@UniqueEmail(message = "El email ya esta registrado")private String email;
Custom validators can inject Spring beans and access the database for complex validation logic.