A Complete Guide to Data Annotations in .NET MVC

In this blog post, we'll explore all the data annotations available in .NET MVC, with examples and best practices for using them effectively. Whether you're a beginner or an experienced .NET MVC developer, you'll learn how to create more secure and reliable applications with data annotations.

Required Attribute:

The Required attribute is used to mark a property as mandatory. If a user submits a form without providing a value for a required field, an error message is displayed. To use this attribute, simply add the [Required] annotation to the property in your model.
public class Employee
{
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Last name is required")]
    public string LastName { get; set; }
}

StringLength Attribute:

The StringLength attribute is used to limit the length of a string property. This attribute takes two parameters - MinimumLength and MaximumLength - which define the acceptable length range for the property.
public class Employee
{
    [Required(ErrorMessage = "First name is required")]
    [StringLength(50, MinimumLength = 2, ErrorMessage = "First name must be between 2 and 50 characters")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Last name is required")]
    [StringLength(50, MinimumLength = 2, ErrorMessage = "Last name must be between 2 and 50 characters")]
    public string LastName { get; set; }
}

Range Attribute:

The Range attribute is used to limit the range of a numeric property. This attribute takes two parameters - Minimum and Maximum - which define the acceptable range for the property.
public class Employee
{
    [Required(ErrorMessage = "Age is required")]
    [Range(18, 60, ErrorMessage = "Age must be between 18 and 60")]
    public int Age { get; set; }
}

RegularExpression Attribute:

The RegularExpression attribute is used to ensure that a property matches a specific regular expression pattern. This attribute takes a single parameter - a regular expression pattern - which is used to validate the property.
public class Employee
{
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Invalid email format")]
    public string Email { get; set; }
}

Compare Attribute:

The Compare attribute is used to ensure that a property's value matches the value of another property in the same model. This attribute takes a single parameter - the name of the property to compare the value to.
public class Employee
{
    [Required(ErrorMessage = "Password is required")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Required(ErrorMessage = "Confirm password is required")]
    [Compare("Password", ErrorMessage = "Password and confirm password must match")]
    [DataType(DataType.Password)]
    public string ConfirmPassword { get; set; }
}

Display Attribute:

The Display attribute is used to specify the name of a property as it should appear in the UI. This is especially useful when the name of the property in the model does not match the desired display name in the UI.
public class Employee
{
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

DataType Attribute:

The DataType attribute is used to specify the data type of a property. This is used for formatting and validation purposes in the UI.
public class Employee
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime HireDate { get; set; }

    [DataType(DataType.Currency)]
    public decimal Salary { get; set; }
}

EmailAddress Attribute:

The EmailAddress attribute is used to validate that a property contains a valid email address.
public class Employee
{
    [EmailAddress(ErrorMessage = "Invalid email address")]
    public string Email { get; set; }
}

Url Attribute:

The Url attribute is used to validate that a property contains a valid URL.
public class Website
{
    [Url(ErrorMessage = "Invalid URL")]
    public string Url { get; set; }
}

CreditCard Attribute:

The CreditCard attribute is used to validate that a property contains a valid credit card number.
public class Order
{
    [CreditCard(ErrorMessage = "Invalid credit card number")]
    public string CreditCardNumber { get; set; }
}

Bind Attribute:

The Bind attribute is used to specify which properties in the model should be included in model binding when a form is submitted. This attribute is often used to prevent over-posting attacks.
public ActionResult Update([Bind(Include = "FirstName,LastName,Email")] Employee employee)
{
    // ...
}

FileExtensions Attribute:

The FileExtensions attribute is used to specify which file types are allowed for a file upload.
public class Document
{
    [FileExtensions(Extensions = "pdf,doc,docx", ErrorMessage = "Only PDF, DOC, and DOCX files are allowed.")]
    public HttpPostedFileBase File { get; set; }
}

Key Attribute:

The Key attribute is used to specify the primary key property for an entity in a database.
public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Phone Attribute:

The Phone attribute is used to validate that a property contains a valid phone number.
public class Customer
{
    [Phone(ErrorMessage = "Invalid phone number")]
    public string Phone { get; set; }
}

ScaffoldColumn Attribute:

The ScaffoldColumn attribute is used to specify whether a property should be displayed in the UI. This is often used to hide fields that should not be edited by users.
public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }

    [ScaffoldColumn(false)]
    public string LastName { get; set; }
}
Here is an example of how to use all of these data annotations in one class in a .NET MVC application:
public class Employee
{
    [Key]
    public int EmployeeId { get; set; }

    [Display(Name = "First Name")]
    [Required(ErrorMessage = "First name is required")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Last name is required")]
    public string LastName { get; set; }

    [Display(Name = "Email Address")]
    [EmailAddress(ErrorMessage = "Invalid email address")]
    public string Email { get; set; }

    [Display(Name = "Phone Number")]
    [Phone(ErrorMessage = "Invalid phone number")]
    public string Phone { get; set; }

    [Display(Name = "Hire Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime HireDate { get; set; }

    [Display(Name = "Salary")]
    [DataType(DataType.Currency)]
    public decimal Salary { get; set; }

    [Display(Name = "Photo")]
    [FileExtensions(Extensions = "jpg,jpeg,png,gif", ErrorMessage = "Only JPG, JPEG, PNG, and GIF files are allowed.")]
    public HttpPostedFileBase Photo { get; set; }

    [ScaffoldColumn(false)]
    public string Notes { get; set; }
}
Here is an example of how to create a view for this model:
@model Employee

@{
    ViewBag.Title = "Create Employee";
}

@ViewBag.Title

@using (Html.BeginForm("Create", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken()
@Html.LabelFor(model => model.FirstName) @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.LastName) @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email) @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Phone) @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.HireDate) @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.HireDate, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Salary) @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Photo) @Html.TextBoxFor(model => model.Photo, new { type = "file", accept = ".jpg, .jpeg, .png, .gif" }) @Html.ValidationMessageFor(model => model.Photo, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Notes) @Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } }) @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
} @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
In this example, we've used the Html.EditorFor and Html.ValidationMessageFor helpers to render form elements and validation messages for each property of the Employee model. We've also included the Html.TextBoxFor helper for the Photo property, since this is a file input field.

Note that we've also included the enctype="multipart/form-data" attribute in the BeginForm method, since we're allowing file uploads. Finally, we've included a Scripts section that includes the necessary scripts for client-side validation.

With this example, you should have a better understanding of how to use data annotations in .NET MVC and create views that utilize these annotations.

In conclusion, data annotations are an essential aspect of .NET MVC development, as they enable developers to validate user input and maintain data integrity. The examples provided in this blog post should serve as a helpful reference for using data annotations in your own projects.
 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice