Data Validation is one of the most important parts of any application. .NET MVC provides special classes to apply validation and data annotation. In this article, we will learn how to apply Data Validation and Annotation in .NET MVC.
Previous Chapter: .NET MVC with SQL Server Database
What Are Data Annotations?
Data annotations are a set of attributes that you can use to decorate your model properties. These attributes define the rules that the data must follow, such as required fields, string length limits, value ranges, and specific patterns.
Understanding Data Annotations in .NET MVC
Data validation and annotation in .NET MVC help ensure that the data users provide is accurate and meets specific criteria before processing or storing. This is crucial for maintaining data integrity and providing a better user experience.
By using the System.ComponentModel.DataAnnotations
namespace, we can enforce data integrity, provide meaningful error messages on UI, and ensure the application runs smoothly without data issues.
Why Use Data Annotations in .NET MVC?
Using data annotations in .NET MVC gives us several benefits:
- Maintainability: Keeping validation rules close to the data model makes it easier to manage and update them.
- Consistency: Applying the same validation rules across different parts of your application ensures consistency.
- User Experience: By providing immediate feedback to users, data annotations help in creating a smoother and more user-friendly experience.
Common Data Annotation Attributes in .NET MVC
Below are some of the Data Annotation attributes we can use in .NET MVC:
- [Required]: Ensures the property is not left empty.
[Required]
public string Name { get; set; }
- [StringLength]: Sets a maximum and/or minimum length for a string.
[StringLength(100, MinimumLength = 10)]
public string Description { get; set; }
- [Range]: Specifies a range for numeric values.
[Range(1, 100)]
public int Age { get; set; }
- [RegularExpression]: Validates the property using a regular expression.
[RegularExpression(@"^[A-Z]+[a-zA-Z]*$")]
public string FirstName { get; set; }
- [EmailAddress]: To validate that the input is a valid Email Address.
[EmailAddress]
public string Email { get; set; }
Adding Data Annotations to Models
Let’s look at an example of a user registration form using data annotations:
using System.ComponentModel.DataAnnotations;
public class UserModel
{
[Required(ErrorMessage = "First name is required")]
[StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last name is required")]
[StringLength(50, ErrorMessage = "Last name cannot be longer than 50 characters")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long")]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Range(18, 100, ErrorMessage = "Age must be between 18 and 100")]
public int Age { get; set; }
}
Creating Custom Validation Attributes
.NET MVC allows us to create custom validation. It means we can define our own validation and related messages for a particular field.
public class CustomDateValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime date = (DateTime)value;
if (date < DateTime.Now)
{
return new ValidationResult("Date must be in the future.");
}
return ValidationResult.Success;
}
}
public class Event
{
[CustomDateValidation]
public DateTime EventDate { get; set; }
}
Implementing IValidatableObject Interface
IValidatableObject is an interface in C# programming, it provides custom validation logic. This interface allows us to implement Validate()
method where we can define our custom validation logic.
In order to use the IValidatableObject
interface, first we will create a model class that implements this interface.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class UserProfile : IValidatableObject
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public DateTime DateOfBirth { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = new List<ValidationResult>();
// Custom validation logic: Date of birth should be in the past
if (DateOfBirth >= DateTime.Now)
{
validationResults.Add(new ValidationResult("Date of Birth must be in the past.", new[] { "DateOfBirth" }));
}
return validationResults;
}
}
Here, we have a model UserProfile which implements the IValidatableObject
interface. Finally, we are defining custom validation logic in the Validate()
method. So, when we submit the form the validate() method is automatically called and then checks for any validation errors.
Client-Side Validation
Enabled Unobtrusive JavaScript validation allows ASP.NET MVC HTML helper extensions to create unique markup to perform validation on the client side.
With unobtrusive JavaScript validation, we can apply client-side validation. Let’s see the following HTML markup:
<input class="form-control valid" data-val="true"
data-val-email="The Email is not a valid e-mail address."
data-val-required="The Email Id is required." id="Email"
name="Email" type="text" value="">
Next Chapter: Filters in .NET MVC
If you are new to .NET MVC, then Please start with this: Build Your First MVC Application in Visual Studio 2022
Keep Following: SharePointCafe.NET