VALIDATE AND PERSIST DATA
VIEW AND CUSTOMIZE VALIDATION ERRORS

Validation is intended to be server-side, this is because the correctness of the data is verified not in the Browser but in the ASP.NET Core application. The problem with what we have implemented so far is that if even the validation is not successful, the user is not notified in any way. Microsoft has set up special TagHelpers to display validation errors.





CLIENT-SIDE VALIDATION
Server-side validation is essential and we should never, ever do without it. It must be said, however, that such validation does not provide a good user experience since the user would only be notified of errors after sending the information to the server. Let’s see how to add client-side validation, that is, before the form is submitted. The asp-for attribute also adds valuable information in the HTML and that pertains to any validation rules we have set up.

To use client-side validation we need a couple of libraries, the first jquery-validation and the second jquery-validation-unobtrusive. This library is from Microsoft.

This is the code for the partial view _Validation, called from View Create.cshtml. You also need to add @RenderSection(“Scripts”, required: false) in the View _Layout.cshtml.

PREVENT THE CREATION OF DUPLICATE CONTENT
It is a matter of going to the database to see if that title already exists. Let us first see how to create a custom Data Annotation.


This is a technique that is not recommended precisely because it does not support dependency injection and asynchronous execution. There are also concurrency issues. Since ASP.NET Core is a Multi-Thread technology it can happen that two competing Threads go to create the same course.

One solution is offered to us by the database by creating a UNIQUE constraint on the title.

We see the TRY-CATCH block that captures the SQLite error due to the violation of the UNIQUE constraint in the CreateCourseAsync method of AdoNetCourseService.

Let’s look at the Controller code.

CHECK CLIENT-SIDE FOR THE EXISTENCE OF A TITLE

Client-side verification and Server-side verification have different purposes, the one done client-side will support the user while typing the form, the server-side one is meant to protect our database and prevent invalid values from getting into it.

Let’s look at Data Annotation, which allows us to send AJAX requests for client-side verification.

Look at all the methods implemented in the controller and application services.

LINK TO CODE ON GITHUB
Download the section code15 or clone the GITHUB repository to have all sections available in your favorite editor.


Leave A Comment