Let us continue with the application that we built in the previous chapter. To do server-side validation, we need to do the following:
ViewModels
model class. The input data is validated against this metadata and the model state is updated automatically.view
method to display the validation message for each of the fields. The span
tag helper with the asp-validation-for
attribute will be used to display the validation error message.view
method is rendered again with the validation error message so that the user can update with valid input data and submit the form again.The Data Annotation attributes defines the validation rules for the properties of the Model
/ViewModel
. If the input data does not match with the attribute definition in the model, the validation will fail, which in turn makes the associated model state invalid.
There are several Data Annotation attributes available to validate the data. The following are the most commonly used Data Annotations attributes:
As Data Annotation attributes are available in the System.ComponentModel.DataAnnotations
namespace, we need to include this namespace. The following is the updated View model code:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Validation.Models; namespace Validation.ViewModels { public class EmployeeAddViewModel { public List<Employee> EmployeesList { get; set; } [Required(ErrorMessage ="Employee Name is required")] public string Name { get; set; } [Required(ErrorMessage ="Employee Designation is required")] [MinLength(5, ErrorMessage = "Minimum length of designation should be 5 characters")] public string Designation { get; set; } [Required] [Range(1000,9999.99)] public decimal Salary { get; set; } } }
We have added Data Annotation attributes for all the three properties—Name
, Designation
, and Salary
.
The ErrorMessage
attribute displays a message to be displayed when the validation fails. If there is a failure of validation and if there is no ErrorMessage
mentioned, the default error message will be displayed.
For each of the fields, we have added a span
tag where the error message is displayed in a red color when the validation fails. When the validation succeeds, there will be no error message displayed. The attribute value of asp-validation-for
represents the field name for which the validation error message has to be displayed. For example, we have used the span
tag with the asp-validation-for
attribute and with the value Name
, which tells ASP.NET MVC to display the validation error message for the Name
field:
<form asp-controller="Employee" asp-action="Index"> <table> <tr> <td><label asp-for="Name"></label></td> <td><input asp-for="Name" /></td> <td><span asp-validation-for="Name" style="color:red"></span></td> </tr> <tr> <td><label asp-for="Designation"></label> </td> <td><input asp-for="Designation" /></td> <td><span asp-validation-for="Designation" style="color:red"></span> </td> </tr> <tr> <td><label asp-for="Salary"></label></td> <td><input asp-for="Salary"></td> <td> <span asp-validation-for="Salary" style="color:red"></span> </td> </tr> <tr> <td colspan="2"><input type="submit" id="submitbutton" value="Submit" /></td> </tr> </table> </form>
The model state is automatically updated based on the Data Annotation attribute specified on our View model and the input data. We are verifying whether the model state is valid in the following Index
method, which is a POST
action method. If the model state is valid (when the validation succeeds), we save the entered data to the database. If the validation fails, then the ModelState
is set to invalid
automatically. Then, we would populate the ViewModel
with the entered data and render the View
method again so that the user can correct the input data and re-submit the data:
[HttpPost] public IActionResult Index(EmployeeAddViewModel employeeAddViewModel) { if (ModelState.IsValid) { using (var db = new EmployeeDbContext()) { Employee newEmployee = new Employee { Name = employeeAddViewModel.Name, Designation = employeeAddViewModel.Designation, Salary = employeeAddViewModel.Salary }; db.Employees.Add(newEmployee); db.SaveChanges(); //Redirect to get Index GET method return RedirectToAction("Index"); } } using (var db = new EmployeeDbContext()) { employeeAddViewModel.EmployeesList = db.Employees.ToList(); } return View(employeeAddViewModel); }
When you run the application after making aforementioned changes and submit the form without entering the values, error messages will be displayed beside the fields as shown in the following screenshot. Please note that, even in the case of a validation error, we display the employees' data in the following table, which is achieved by using the code block in the previous code snippet.
There are a few things to be noted in the previous validation and its error message:
Required
and MinLength
attributes. If there is no data entered for the field, only the required field error message will be displayed. Only when the required field error is resolved (by entering some characters in the field), the second validation error message will be displayed.
The preceding figure depicts the high-level sequence of events in server-side validation and is described as follows:
view
method is mapped to the data in the model or View model.