Summary
Highlights
Spring MVC simplifies validation through annotations and built-in features, eliminating the need for custom logic. Validation annotations should always be placed on a Data Transfer Object (DTO) to avoid code smells and maintain a clean architecture.
Various annotations like @NotEmpty, @NotNull, @Email, @Min, and @Max can be applied to fields in a DTO. The video demonstrates using @NotEmpty for fields like 'title', 'photo URL', and 'content'. To activate these annotations, the @Valid keyword must be added to the controller method's DTO parameter, and a BindingResult object is used to check for errors.
To implement validation, first add the 'spring-boot-starter-validation' dependency. Once added, annotations can be applied to DTO fields along with custom error messages. In the controller, the BindingResult object checks for errors using `result.hasErrors()`. If errors exist, the user is redirected back to the form, and error messages are displayed on the HTML page using `th:if` and `th:errors` in Thymeleaf.
The video walks through adding validation to an 'edit' form. This involves adding the @Valid annotation to the DTO in the controller and the BindingResult. It then shows how to display specific error messages for 'title', 'photo URL', and 'content' fields using Thymeleaf's `th:if` and `th:errors` attributes, dynamically showing issues to the user.
Validation is crucial for 'create' operations to prevent bogus data. The process for 'create' is similar to 'edit': using a DTO, adding the @Valid annotation and BindingResult, and displaying errors with Thymeleaf. The controller logic includes an if-else statement to check `result.hasErrors()` and redirect back to the create page if validation fails, while also adding the DTO to the model.
The video concludes by demonstrating the validation in action for both 'create' and 'edit' functions. It shows how leaving fields empty triggers the validation errors and how entering valid data allows the operations to succeed, confirming that the validation setup is working correctly.