Validation and Views
While our application is properly handing errors, we need to display the error messages so that the users know what information they should be adding. Client-side validation like this can prevent faulty data submissions.
Displaying Error Messages in our View
Create a separate span element in the form. In the
<span> tag, we can add
asp-validation-for to specify which property’s validation error messages should be displayed if the conditions are not met.
We don’t have to add anything else to display error messages, because that validation is already built in!
Now when we run our application and enter a bad event name or forget our description, we get the error message displaying what we should be entering!
If we pass our validation, we should be redirected to the
/Events view and see the new event added to the list!
Changing the Color of Error Messages
Making error messages a different color, such as red, is a common technique to catch the attention of the user. We can do that by using unobtrusive validation methods, such as using a third-party library.
jQuery Unobtrusive Validation library. contains scripts that will perform validation tasks, such as updating the color of error messages. To utilize this library, we need to point to it in our
_Layout.cshtml page and then add more attributes to our Views.
To utilize the library, we need to add the following references to it within the
Add View, you will need to create more class attributes for the library to target.
Note in line 10 the addition of
class="form-control" and in line 11
class="text-danger". These attributes will be noted by the jQuery Unobtrusive Validation library and print our red if the client does not meet the requirements.
You can read more about client-side validation and the jQuery Unobtrusive Validation library check out the documentation .
Check Your Understanding
True or False: In order to implement validation, all three elements of MVC applications are involved.