w3resource

Implement Data Validation in MVC


In the past tutorials we learnt how to generate form elements using HtmlHelper classes. In section, we will learn how to validate those form elements we created using data annotation attributes.

We have created an Edit view for Activities in the previous section. Now, we will implement data validation in the Edit view, which will display validation messages on the click of Save button if the required fields are left blank.

Data Annotations

ASP.NET MVC uses Data Annotations attributes to implement validations. Data Annotations includes built-in validation attributes for different validation rules, which can be applied to the properties of model class.

ASP.NET MVC framework will automatically enforce these validation rules and display validation messages in the corresponding view.

The Data Annotations attributes included in System.ComponentModel.DataAnnotations namespace. The table below consists of DataAnnotations validation attributes.

Attribute Description
Required Indicates that the property is a required field
StringLength Defines a maximum length for string field
Range Defines a maximum and minimum value for a numeric field
RegularExpression Specifies that the field value must match with specified Regular Expression
CreditCard Specifies that the specified field is a credit card number
CustomValidation Specified custom validation method to validate the field
EmailAddress Validates with email address format
FileExtension Validates with file extension
MaxLength Specifies maximum length for a string field
MinLength Specifies minimum length for a string field
Phone Specifies that the field is a phone number using regular expression for phone numbers

Let's start by implementing validation in Edit view for activities.

Step 1: First of all, apply DataAnnotation attribute on the properties of Activity model class. We want to validate that ActivityName and Status is not blank. Also, Status should be between 5 and 50.

If you are a bit lost on how we created the model, you can refer to the model section of our tutorial series to bring yourself up to speed.

//Example: Apply DataAnnotation Attributes
public class Student
{
    public int Id { get; set; }
     
    [Required]
    public string ActivityName { get; set; }

    [Range(0,1)]
    [Required]
    public int Status { get; set; }
}

You can also apply multiple DataAnnotations validation attributes to a single property if required.

In the above example, we have applied a Required attribute to the ActivityName property. So now, the MVC framework will automatically display the default error message, if the user tries to save the Edit form without entering the Student Name. In the same way, the Range attribute is applied with a min and max value to the Status property. This will validate and display an error message if the user has either not entered Status or entered a status less than 0 or more than 1.

Step 2: Create the GET and POST Edit Action method in the same as previous section. The GET action method will render Edit view to edit the selected student and the POST Edit method will save edited activity as shown below.

Example: Edit Action methods:

using MVC_BasicTutorials.Models;
namespace MVC_BasicTutorials.Controllers
{
    public class ActivityController : Controller
    {
        public ActionResult Edit(int id)
        {
            var act = activityList.Where(a => a.Id == id).FirstOrDefault();
            return View(act);
        }   
        [HttpPost]
        public ActionResult Edit(Activity act)
        {
            if (ModelState.IsValid) { 
                //write code to update activity
                return RedirectToAction("Index");
            }
            return View(act);
        }
    }
}

As you can see in the POST Edit method, we first check if the ModelState is valid or not. If ModelState is valid then update the student into database, if not then return Edit view again with the same student data.

ModelState.IsValid determines that whether submitted values satisfy all the DataAnnotation validation attributes applied to model properties.

Step 3: Now, create an Edit view for Activity.

To create an Edit view, right click inside Edit action method -> click Add View..

In the Add View dialogue, keep the view name as Edit. (You can change as per your requirement.)

asp.net create an Edit view for Activity

Select the Edit template in the Template dropdown and also select ActivityTab Model class as shown below.

Now, click Add to generate Edit view under View/Activites folder. Edit.cshtml will be generated as shown below.

Edit.cshtml:

@model ActivityTab.Models.Activity

@{
    ViewBag.Title = "Edit";
}
<h2>Edit Activites</h2>


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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Status, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Status, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Status, "", 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>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

As you can see in the above Edit.cshtml, it calls Html Helper method ValidationMessageFor for every field and ValidationSummary method at the top. ValidationMessageFor is responsible to display error message for the specified field. ValidationSummary displays a list of all the error messages at once.

So now, it will display default validation message when you submit an Edit form without entering a ActivitiesName or Status.

Thus, you can implement validations by applying various DataAnnotation attributes to the model class and using ValidationMessage() or ValidationMessageFor() method in the view.



Inviting useful, relevant, well-written and unique guest posts