Data Annotations in ASP.NET Core MVC
Introduction of Data Annotations in ASP.NET Core MVC
In .NET applications, Data Annotations are attributes applied directly to model properties to enforce validation, set display rules, or even customize database mappings. These annotations are extensively used in ASP.NET Core MVC and Entity Framework Core (EF Core) to validate user input and maintain data consistency in an application. Data Annotations are widely used in Entity Framework Core, ASP.NET Core MVC, Web APIs, and Razor Pages applications, making them essential to model-driven development.
Key Benefits of Data Annotations in ASP.NET Core MVC
- Validation — Ensures data integrity by applying rules like [Required], [Range], and [EmailAddress].
- Display Formatting — Customizes UI labels and formats using [Display(Name=”Custom Label”)].
- Database Mapping — Influences how Entity Framework Core maps properties to database columns.
- Client-Side & Server-Side Validation — Automatically integrates with jQuery validation for seamless user input checks.
Types of Data Annotations in ASP.NET Core MVC
1. Validation Annotations
2. Formatting Annotations
3. Display and Metadata Annotations
4. Database Mapping Annotations
Here I describe 15 Essential Data Annotations in ASP.NET Core MVC with Examples .
Validation Annotations in ASP.NET Core MVC
- [Required] attribute in ASP.NET: Ensures that a field is not empty.
Example:
public class Student { [Required(ErrorMessage = "Name is required")] public string Name { get; set; } }
2. [StringLength] attribute in ASP.NET: Defines maximum length for a string. If we do not specify taking full length, that wastes our database space.
Example:
public class Student { [StringLength(100, MinimumLength = 3, ErrorMessage = "Name should be between 3 and 100 characters.")] public string Name { get; set; } }
3. [MaxLength] and [MinLength] attributes in ASP.NET: Specifies minimum and maximum lengths for string properties.
Example:
public class Course { [MaxLength(50, ErrorMessage = "Title cannot exceed 50 characters.")] public string Title { get; set; } }
4. [Range] attribute in ASP.NET: Restricts a numerical property to a specified range.
Example:
public class Student { [Range(18, 60, ErrorMessage = "Age must be between 18 and 60.")] public int Age { get; set; } }
5. [RegularExpression] attribute in ASP.NET: Ensures a property matches a specified regular expression pattern.
Example:
public class User { [RegularExpression(@"^[a-zA-Z\s]*$", ErrorMessage = "Only alphabetic characters are allowed.")] public string FullName { get; set; } }
6. [EmailAddress] attribute in ASP.NET: Verifies that the property contains a valid email address.
Example:
public class User { [EmailAddress(ErrorMessage = "Invalid email address format.")] public string Email { get; set; } }
7. [Url] attribute in asp.net: Ensures the property contains a valid URL.
Example:
public class Website { [Url(ErrorMessage = "Invalid URL format.")] public string WebsiteUrl { get; set; } }
8. [Compare] attribute in ASP.NET: [Compare] Used to compare two fields. It’s commonly used for password confirmation.
Example:
public class User { public string Password { get; set; } [Compare("Password", ErrorMessage = "Passwords do not match.")] public string ConfirmPassword { get; set; } }
9. [Phone] attribute in asp.net: Ensures that the property contains a valid phone number.
Example:
public class Contact { [Phone(ErrorMessage = "Invalid phone number.")] public string PhoneNumber { get; set; } }
10.[CreditCard] attribute in ASP.NET: Validates that the property contains a valid credit card number.
Example:
public class Payment { [CreditCard(ErrorMessage = "Invalid credit card number.")] public string CreditCardNumber { get; set; } }
Formatting Annotations in ASP.NET CORE MVC:
11. [DataType] attribute in ASP.NET: Specifies the type of data (e.g., date, currency, email, or URL) for better formatting and presentation in the UI.
Example:
public class Student { [DataType(DataType.Date)] public DateTime DateOfBirth { get; set; } [DataType(DataType.Currency)] public decimal Fees { get; set; } }
Display and Metadata Annotation:
12. [Display] attribute in ASP.NET: Allows customization of how a property is displayed in the UI.
Example:
public class Student { [Display(Name = "Full Name")] public string Name { get; set; } }
13. [DisplayName] attribute in ASP.NET: This is used to define a user-friendly display name, often used in model binding.
Example:
public class Student { [DisplayName("Student Name")] public string Name { get; set; } }
Database Mapping Annotation in ASP.NET Core MVC
14. [Key] attribute in ASP.NET: Specifies the primary key of an entity.
Example:
public class Student { [Key] public int StudentId { get; set; } }
15. [Timestamp] attribute in ASP.NET: Used to mark a property that should be used for concurrency checks, ensuring that records are not updated simultaneously.
Example:
public class Student { [Timestamp] public byte[] RowVersion { get; set; } }
In conclusion, Data Annotations in ASP.NET Core are essential for enforce business rules, improving maintainability, and ensuring data integrity without writing extensive custom validation logic.
Back to Blogs