Tutorialsteacher

Follow Us

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.

Validation

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.

AttributeUsage
RequiredSpecifies that a property value is required.
StringLengthSpecifies the minimum and maximum length of characters that are allowed in a string type property.
RangeSpecifies the numeric range constraints for the value of a property.
RegularExpressionSpecifies that a property value must match the specified regular expression.
CreditCardSpecifies that a property value is a credit card number.
CustomValidationSpecifies a custom validation method that is used to validate a property.
EmailAddressValidates an email address.
FileExtensionValidates file name extensions.
MaxLengthSpecifies the maximum length of array or string data allowed in a property.
MinLengthSpecifies the minimum length of array or string data allowed in a property.
PhoneSpecifies 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 className="form-horizontal">
        <h4>Student</h4>
        <hr />
        <b>@Html.ValidationSummary(true, "", new { @class = "text-danger" })</b>
        @Html.HiddenFor(model =&gt; model.StudentId)

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

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

        <div className="form-group">
            <div className="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" className="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.