Form validation in Spring Boot is handled declaratively with Jakarta Bean Validation annotations on the model, triggered automatically when a controller parameter is marked with @Valid.
Key Points: • Constraint annotations like @NotNull, @Size, @Email, and @Min/@Max are placed directly on DTO or entity fields. • @Valid on a controller method parameter tells Spring to run validation before the method body executes. • If validation fails, Spring throws a MethodArgumentNotValidException, which by default returns a 400 response detailing which fields failed and why. • A custom @ExceptionHandler (or @ControllerAdvice) can format these validation errors into a cleaner, application-specific error response. • Custom constraints can be added via a custom annotation and ConstraintValidator when built-in ones aren't sufficient, such as cross-field rules.
Example: A registration form DTO annotated with @NotBlank on name and @Email on email will automatically reject a submission missing the name or with a malformed email, returning a 400 response listing both problems without any manual if-checks in the controller.
Code Example:
public class RegistrationDto {
@NotBlank
private String name;
@Email
private String email;
}
@PostMapping("/register")
public ResponseEntity<?> register(@Valid @RequestBody RegistrationDto dto) {
return ResponseEntity.ok("registered");
}Interview Tip: A concise interview answer is:
"I annotate the DTO fields with Bean Validation constraints like @NotBlank, @Size, and @Email, then add @Valid to the controller parameter so Spring runs validation automatically before the handler executes. Failures throw MethodArgumentNotValidException, which I catch in a @ControllerAdvice to return clean, consistent error responses."