Implement Data Validation in MVC

Here, you will learn how to implement the data validation and display validation messages on the violation of business rules in an ASP.NET MVC application.

The following image shows how the validation messages will be displayed if Name or Age fields are blank while creating or editing data.

Display Validation Messages

Validation using Data Annotation Attributes

ASP.NET MVC includes built-in attribute classes in the System.ComponentModel.DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.

The following table lists all the data annotation attributes which can be used for validation.

Attribute Usage
Required Specifies that a property value is required.
StringLength Specifies the minimum and maximum length of characters that are allowed in a string type property.
Range Specifies the numeric range constraints for the value of a property.
RegularExpression Specifies that a property value must match the specified regular expression.
CreditCard Specifies that a property value is a credit card number.
CustomValidation Specifies a custom validation method that is used to validate a property.
EmailAddress Validates an email address.
FileExtension Validates file name extensions.
MaxLength Specifies the maximum length of array or string data allowed in a property.
MinLength Specifies the minimum length of array or string data allowed in a property.
Phone Specifies that a property value is a well-formed phone number.

Let's see how to use these attributes to display validation messages on the view.

The following is the Student model class.

Example: Apply DataAnnotation Attributes
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}

We want to implement validations for StudentName and Age property values. We want to make sure that users do not save empty StudentName or Age value. Also, age should be between 10 to 20.

The Required attribute is used to specify that the value cannot be empty. The Range attribute is used to specify the range of values a property can have. We will use the Required attribute on the StudentName to make it mandatory for the user to provide value and Range attribute to make sure the user enters value between 10 to 20, as shown below.

Example: Apply DataAnnotation Attributes
public class Student
{
    public int StudentId { get; set; }
     
    [Required]
    public string StudentName { get; set; }
       
    [Range(10, 20)]
    public int Age { get; set; }
}

The above attributes define the metadata for the validations of the Student class. This alone is not enough for the validation. You need to check whether the submitted data is valid or not in the controller. In other words, you need to check the model state.

Use the ModelState.IsValid to check whether the submitted model object satisfies the requirement specified by all the data annotation attributes. The following POST action method checks the model state before saving data.

Example: Edit Action methods:
public class StudentController : Controller
{
    public ActionResult Edit(int id)
    {
        var stud = ... get the data from the DB using Entity Framework

        return View(stud);
    }

    [HttpPost]
    public ActionResult Edit(Student std)
    {
        if (ModelState.IsValid) { //checking model state
            
            //update student to db
            
            return RedirectToAction("Index");
        }
        return View(std);
    }
}

Now, create an edit view as shown here. The following is a generated edit view using the default scaffolding template.

Edit View: Edit.cshtml
@model MVC_BasicTutorials.Models.Student

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.StudentId)

        <div class="form-group">
            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

In the above view, it calls the HTML Helper method ValidationMessageFor() for every field and ValidationSummary() method at the top. The ValidationMessageFor() displays an error message for the specified field. The ValidationSummary() displays a list of all the error messages for all the fields.

In this way, you can display the default validation message when you submit a form without entering StudentName or Age, as shown below.

Validation

Learn how to implement client side validation in ASP.NET MVC.

Want to check how much you know ASP.NET MVC?