Can you describe form validation in Spring MVC?

Form validation in Spring MVC uses Java Bean Validation annotations combined with @Valid to enforce data rules on submitted form data, capturing any violations through a BindingResult instead of letting invalid data reach the business layer.

Key Points: • Constraint annotations like @NotNull, @Size, @Email, and @Pattern are placed directly on the model object's fields to declare validation rules. • @Valid on the controller's model-attribute parameter triggers those constraints to be checked during binding. • A BindingResult parameter, declared immediately after the validated object, captures any violations instead of causing an exception. • When hasErrors() is true, the controller typically returns the same form view, and error messages are rendered next to the relevant fields. • Custom validators implementing Validator can enforce cross-field or business-rule checks that annotations alone can't express.

Example: A signup form's User object annotated with @NotBlank on username and @Email on email will fail binding if either is missing or malformed, and the controller sends the user back to the signup page with field-specific error messages instead of creating an invalid account.

Code Example:

@PostMapping("/signup")
public String signup(@Valid @ModelAttribute User user, BindingResult result) {
    if (result.hasErrors()) {
        return "signupForm";
    }
    userService.save(user);
    return "redirect:/welcome";
}

Interview Tip: A concise interview answer is:

"I put Bean Validation annotations like @NotNull and @Size directly on the form-backing object, then add @Valid in the controller method to trigger them, paired with a BindingResult to capture any violations. If there are errors, I return the user to the same form view with the error messages instead of proceeding."