The Data Annotation attribute defines the validation rules for the properties of the Model/ViewModel. If the input data does not match the attribute definition in the model, the validation will fail, which in turn makes the associated model state invalid. The reason for adding annotations to ViewModels is that we expose ViewModels to the outside world, not the models. Also, we don't want to pollute our business classes with ASP.NET-specific attributes.
There are several Data Annotation attributes available to validate the data. The following are the most commonly-used Data Annotation attributes:
- Required: This attribute indicates that the property is required.
- Range: This attribute defines the minimum and maximum constraints.
- MinLength: This defines the minimum length a property must have in order for the validation to succeed.
- MaxLength: As the name implies, this attribute defines the maximum length of the property. If the length of the property value exceeds the maximum length, the validation will fail.
- RegularExpression: We can use a regular expression for data validation if we use this attribute.
As Data Annotation attributes are available in the System.ComponentModel.DataAnnotations namespace, we need to include this namespace. The following is the updated ViewModel code from Chapter 4, Models:
Go to https://goo.gl/EgT2vC to access the code.
using MVCEF.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MVCEF.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 that will 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.
The drawbacks of using attributes is that it can only handle literals that are available at compile time. If we need more dynamic validation, we can derive from ValidationAttribute and add our own logic. Also, it is possible to use resource files to localize the items.