Understand and implement Data Annotations in ASP.NET Core to validate and customize your models efficiently.
Introduction
Data Annotations in ASP.NET Core provide a simple yet powerful way to validate and customize model properties. Whether you're building a small application or a complex system, Data Annotations ensure your data meets specific rules and guidelines, enhancing overall application reliability and user experience.
What Are Data Annotations?
Data Annotations are a set of attributes in the System.ComponentModel.DataAnnotations
namespace that can be applied to model properties to define metadata, validation rules, and display formats. They are commonly used in ASP.NET Core MVC and Razor Pages for model validation and UI customization.
The following diagram illustrates Data Annotations in ASP.NET Core:

Why Use Data Annotations?
Data Annotations provide several benefits:
- Enable server-side and client-side validation.
- Reduce boilerplate code for validation logic.
- Integrate seamlessly with Entity Framework for database schema generation.
- Improve code readability and maintainability.
Validation Attributes
Validation attributes ensure that input data meets specific criteria before processing. Below are some commonly used validation attributes:
[Required]
: Ensures a property is not null or empty.[StringLength]
: Specifies the minimum and maximum length of a string.[Range]
: Validates that a numeric value falls within a specified range.[RegularExpression]
: Ensures a property matches a specific regular expression pattern.[EmailAddress]
: Validates an email address format.[Compare]
: Compares two properties for equality (e.g., password and confirm password).
public class UserViewModel
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }
[Range(18, 60, ErrorMessage = "Age must be between 18 and 60.")]
public int Age { get; set; }
}
Display Attributes
Display attributes are used to customize how model properties appear in the user interface. These attributes include:
[Display]
: Sets the display name, group name, description, and other metadata.[DataType]
: Specifies the type of data (e.g., date, currency).[DisplayFormat]
: Customizes formatting for date, time, and numbers.
public class ProductViewModel
{
[Display(Name = "Product Name")]
public string Name { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
}
Creating Custom Validation Attributes
You can create custom validation attributes by inheriting from the ValidationAttribute
class:
public class AgeValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int age = (int)value;
if (age < 18 || age > 60)
{
return new ValidationResult("Age must be between 18 and 60.");
}
return ValidationResult.Success;
}
}
Real-World Example
Here is a complete example of a model and its usage in a Razor Page:
// Model
public class EmployeeViewModel
{
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
[Range(18, 60)]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
}
// Razor Page
public class EmployeeModel : PageModel
{
[BindProperty]
public EmployeeViewModel Employee { get; set; }
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
// Save to database
return RedirectToPage("Success");
}
}
Best Practices for Using Data Annotations
- Use meaningful error messages for better user feedback.
- Avoid overloading models with too many annotations.
- Test both server-side and client-side validation.
- Use custom validation for complex business rules.
Conclusion
Data Annotations in ASP.NET Core simplify the process of validating and customizing models, reducing the need for extensive custom logic. By understanding and applying the attributes discussed here, you can create robust and user-friendly applications with minimal effort.