Spring MVC - 10. Validation

Share

Summary

This video tutorial explains how to implement validation in Spring MVC applications using annotations and the BindingResult object. It covers adding validation dependencies, applying annotations to DTOs, and displaying error messages in HTML forms for both create and update operations.

Highlights

Introduction to Spring MVC Validation
00:00:00

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.

Using Validation Annotations
00:01:00

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.

Setting up Validation and Displaying Errors
00:02:39

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.

Implementing Validation for Edit Functionality
00:04:42

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.

Implementing Validation for Create Functionality
00:07:15

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.

Testing Validation
00:10:47

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.

Recently Summarized Articles

Loading...