Applying Validations in Asp.Net MVC

In my previous article, we discuss how to save data in the database in Asp.Net MVC with a simple example. Today we discuss how we can apply validations for input data. Open Microsoft Visual Studio 2015 and create MVC application as explained in the previous article. Search for Product class in the solution and open Product.cs class.

.Net framework is providing several attributes for adding the validations for model class. We can use Required, Range, and several other attributes to apply validations as shown below.

namespace FirstMVCApp.Models

{

    using System;

    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations;   

    public partial class Product

    {

        [Required, Range(1,1000)]

        public int Id { get; set; } 

        [Required, StringLength(50)]

        public string ProductName { get; set; } 

        [Required]

        public string ProductDesc { get; set; } 

        [Required, StringLength(50)]

        public string ProductUrl { get; set; }

    }

} 

In the above class, we have applied Required attribute for every property. For Id property, we have mentioned range between 1 and 1000 by using Range attribute. That means if we enter Id value outside of the given range Asp.Net MVC framework throws the error. We can directly apply RangeAttribute without Required attribute also.  For ProductName and ProductUrl properties we have applied StringLengthAttribute to restrict the string length.

Before passing the data to the database, we have to check whether the model is valid or not in the controller by using ModelState.IsValid property in Controller as shown below.

using FirstMVCApp.Models;

using System.Web.Mvc; 

namespace FirstMVCApp.Controllers

{

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            return View();

        }

        [HttpGet]

        public ActionResult CreateProduct()

        {

            return View();

        }

        [HttpPost]

        public ActionResult CreateProduct(Product product)

        {

            if (ModelState.IsValid)

            {

                var db = new ECommerceEntities();

                db.Products.Add(product);

                db.SaveChanges();

            }

            return View(product);

        }

    }

}

So, whenever the request is invalid it just displays the product view again without calling database for save operation. If the request is valid ModelState.IsValid returns and data saved in database.

Now we have to display the error message on the browser whenever the user enters incorrect data. For that, we have to display validation message for each model property if any by using ValidationMessageFor(). Moreover, we can also display a summary of all properties validations by using ValidationSummary() in the view as shown below.

@model FirstMVCApp.Models.Product

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

 <head>

    <meta name="viewport" content="width=device-width" />

    <title>Create Product</title>

</head>

<body>

    <div>

        @using (Html.BeginForm())

        {

            @Html.ValidationSummary()

            <p>

                @Html.LabelFor(model => model.Id)

                @Html.EditorFor(model => model.Id)

                @Html.ValidationMessageFor(model => model.Id)

            </p>

            <p>

                @Html.LabelFor(model => model.ProductName)

                @Html.EditorFor(model => model.ProductName)

                @Html.ValidationMessageFor(model => model.ProductName)

            </p>

            <p>

                @Html.LabelFor(model => model.ProductDesc)

                @Html.EditorFor(model => model.ProductDesc)

                @Html.ValidationMessageFor(model => model.ProductDesc)

            </p>

            <p>

                @Html.LabelFor(model => model.ProductUrl)

                @Html.EditorFor(model => model.ProductUrl)

                @Html.ValidationMessageFor(model => model.ProductUrl)

            </p>

            <p>

                <input type="submit" value="Create Product" />

            </p>

        }

    </div>

</body>

</html> 

Run the application and submit the form without entering any data by clicking on “Create Product” button. Asp.Net MVC framework displays the error message as shown below and it will not submit the data to database.

Even you can display custom error message by applying ErrorMessage property for Product model class as shown below.

namespace FirstMVCApp.Models

{

    using System;

    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations; 

    public partial class Product

    {

        [Required(ErrorMessage = "Please enter Product Id"),

          Range(1, 1000, ErrorMessage = "Product Id Should be between 1 and 1000")]

        public int Id { get; set; } 

        [Required(ErrorMessage = "Please enter Product Name"),

          StringLength(50, ErrorMessage = "Product Name length should not be more than 50")]

        public string ProductName { get; set; } 

        [Required(ErrorMessage = "Please enter Product Description")]

        public string ProductDesc { get; set; } 

        [Required(ErrorMessage = "Please enter Product URL"),

           StringLength(50, ErrorMessage = "Product URL length should not be more than 50")]

        public string ProductUrl { get; set; }

    }

}

Run the application and submit the form without entering any data. It displays custom error messages as shown below.

If you have any date property in your model class, you can apply RangeAttribute as shown below.

namespace FirstMVCApp.Models

{

    using System;

    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations; 

    public partial class Product

    {

        [Required(ErrorMessage = "Please enter Product Id"),

          Range(1, 1000, ErrorMessage = "Product Id Should be between 1 and 1000")]

        public int Id { get; set; } 

        [Required(ErrorMessage = "Please enter Product Name"),

          StringLength(50, ErrorMessage = "Product Name length should not be more than 50")]

        public string ProductName { get; set; } 

        [Required(ErrorMessage = "Please enter Product Description")]

        public string ProductDesc { get; set; } 

        [Required(ErrorMessage = "Please enter Product URL"),

           StringLength(50, ErrorMessage = "Product URL length should not be more than 50")]

        public string ProductUrl { get; set; } 

        [Required(ErrorMessage = "Please enter Product Available Time"),

        Range(typeof(DateTime), "10/31/2016", "12/31/2017",

         ErrorMessage = "Product Available time should be between 10/31/2016 12/31/2017")]

        public string ProductAvailableTime { get; set; }

    }

}

As given above, we are using typeof attribute to specify the data type for Range attribute. Add the ProductAvailableTime in the view. Run the application and submit the form by entering out of range date for product available time. It displays the error message as below.

We can also add the validations in Controller class also by using ModelState.AddModelError() method.

[HttpPost]

public ActionResult CreateProduct(Product product)

{

         if (product.Id < 1 || product.Id > 1000)

         {

               ModelState.AddModelError("Id", "Product Id Should be between 1 and 1000");

          }

          if (ModelState.IsValid)

          {

               var db = new ECommerceEntities();

               db.Products.Add(product);

               db.SaveChanges();

           }

          return View(product);

}

But we have to add validations in model class and it is the best practice.