Implementing Robust Input Validation in ASP.NET MVC using Data Annotations
Learn how to perform data validation in ASP.NET MVC using data annotations. This tutorial demonstrates adding validation rules directly to your model properties, handling form submissions, and displaying validation messages to the user, ensuring data integrity and a positive user experience.
Input Validation in ASP.NET MVC
Introduction to MVC Data Validation
Validating user input is crucial for building robust and secure web applications. ASP.NET MVC provides several ways to implement data validation, including using data annotations directly in your model classes. Data annotations are attributes you add to model properties to specify validation rules. The MVC framework automatically applies these rules when processing form submissions.
Common Validation Annotations in ASP.NET MVC
Annotation | Description |
---|---|
[Required] |
Specifies that a field is required. |
[DisplayName] |
Sets the display name for a field. |
[StringLength] |
Specifies the maximum length of a string field. |
[Range] |
Specifies the allowed range for a numeric field. |
[Bind] |
Specifies which properties to include or exclude when binding model data. |
[ScaffoldColumn] |
Controls whether a property is included in scaffolded forms. |
[MaxLength] |
Specifies the maximum length for a field (similar to StringLength). |
[EmailAddress] |
Validates email addresses. |
[DataType] |
Specifies the data type (e.g., PhoneNumber, Date). |
[RegularExpression] |
Specifies a regular expression pattern for validation. |
Example: Validating a Student Model
Let's create a simple model (Student.cs
) with validation annotations and a controller (StudentsController.cs
) and view (Index.cshtml
) to demonstrate.
Student.cs
using System.ComponentModel.DataAnnotations;
namespace MvcApplicationDemo.Models
{
public class Student
{
public int ID { get; set; }
[Required(ErrorMessage = "Name is required")]
[MaxLength(12)]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Contact is required")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string Contact { get; set; }
}
}
StudentsController.cs
// ... (Controller code would be added here. This would include the ActionResult for the Index view.) ...
Index.cshtml
@model MvcApplicationDemo.Models.Student
@{
ViewBag.Title = "Index";
}
<p>Index</p>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<p>Student</p>
<!-- ... (Form fields for Name, Email, Contact using Html.LabelFor, Html.EditorFor, and Html.ValidationMessageFor) ... -->
}
<p>@Html.ActionLink("Back to List", "Index")</p>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Output (Showing Validation)
(Screenshots illustrating the form with validation messages displayed when invalid data is entered would be included here.)