Custom Validation using Data Annotations Attribute in Asp.Net MVC with Example

Here we will learn how to use custom validation in asp.net with data annotation attributes with example. As we had seen various other validations such as Remote Validation and Data Annotations to validate data, let’s create some custom validation because every business application has its own validation rules to be applied.

 

Generally, in asp.net mvc data annotation attributes are used to validate the user inputs (required, range, Regular expression, etc.). These are the default validations provided by the MVC. If you want your own Custom Validation, we need to inherit from ValidationAttribute and create it.

Create Asp.Net MVC Application

First, create a basic asp.net MVC 4 application with the name CustomValidationinMVC for that Open visual studio à Go to File àSelect New àSelect Project like as shown below. 

 

create new asp.net mvc project from visual studio 2012

 

After that, you will see a new dialog for selecting your Template and Project type. Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application. Here we are giving the name “CustomValidationinMVC” then finally click on the ok button.

 

custom validations example in asp.net mvc using data annotations attribute

 

After naming it, click on OK. After that, a new dialog will popup for selecting a template. In that, select the Basic template and click ok.

 

select custom basic template in asp.net mvc with example

 

After creating the application, our project structure like as shown below.

 

custom validations project structure in asp.net mvc with example

 

After creating the application, let’s work with Create Model because we will use the Code first approach of asp.net mvc in this tutorial.

Add New Model to MVC Application

For adding Model, right-click on Model folder select Add, inside that select Class like shown below. 

 

adding new model to models folder in asp.net mvc

 

After Clicking on class, an Add New Item dialog will pop up with class select and asking for class name here, we are going to enter the class name as “Orders”.

 

Give name to model in data annotations in asp.net mvc application

 

After entering the class name, click on the Add button. An order class is added to your project with some default code u can see below code snippet.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class Orders

{

 

}

}

Now let’s add properties to this class.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class Orders

{

public int OrderID { get; set; }

public int VegMeals { get; set; }

public int NonVegMeals { get; set; }

public decimal Servicetax { get; set; }

 

public decimal TotalAmount { get; set; }

public DateTime shippeddate { get; set; }

}

}

After adding Properties, we have to add Validation. We need to create a new class and inherit ValidationAttribute, and this class will have the business logic of our custom attribute. As we have added the Order class similar way, we will add another class with ShippeddateValidate.cs.

 

add new class as model in asp.net mvc folder

 

After entering the class name, click on the Add button. A ShippeddateValidate class is added to your project with some default code u can see below code snippet.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class ShippeddateValidate

{

 

}

}

Now let’s inherit from ValidationAttribute. For that, we need to add the namespace System.ComponentModel.DataAnnotations.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class ShippeddateValidate : ValidationAttribute

{

 

}

}

After inheriting, now override the virtual method IsValid and write our custom logic here. Here we are going to validate Shippeddate Property.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class ShippeddateValidate : ValidationAttribute

{

protected override ValidationResult IsValid(object value, ValidationContext validationContext)

{

DateTime CurrentDate = DateTime.Now;

string Message = string.Empty;

if (Convert.ToDateTime(value) < CurrentDate)

{

Message = "Shipped Date cannot be less than current date";

return new ValidationResult(Message);

}

return ValidationResult.Success;

}

}

}

In this code snippet, I will check the date selected by the user and against the current date. If the date is less than the defined value, we will get an error message. After completion of adding custom logic, let’s add this custom validation (ShippeddateValidate) to Property.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace CustomValidationinMVC.Models

{

public class Orders

{

public int OrderID { get; set; }

public int VegMeals { get; set; }

public int NonVegMeals { get; set; }

public decimal Servicetax { get; set; }

 

[DataType(DataType.Date)]

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

[ShippeddateValidate]

public DateTime shippeddate { get; set; }

}

}

After completing with adding custom validation (ShippeddateValidate) to Property, let’s create a controller.

Add New Controller to MVC Application

For adding Controller, right-click on the Controller folder inside that select Add and then select Controller.

 

Add controller in asp.net mvc custom validations application

 

After clicking on the controller, a new dialog will pop up with the name Add Controller.

 

Give name to controller in remote validations application in asp.net mvc

 

In Template, select the “Empty MVC controller” and finally click on the Add button. Some default code is generated after adding a controller class. Here in this controller code, we made some manual configuration by adding Action Selector [HttpGet], [HttpPost] with a New Action Method Index with Orders model parameter as input.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using CustomValidationinMVC.Models;

 

namespace CustomValidationinMVC.Controllers

{

public class OrderController : Controller

{

//

// GET: /Order/

[HttpGet]

public ActionResult Index()

{

return View();

}

[HttpPost]

public ActionResult Index(Orders objorder)

{

return View(objorder);

}

}

}

Add New View to MVC Application

For Adding View, right-click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in the below snapshot, we selected View engine as Razor, and we are going to create a strongly typed view for that I have selected Model class Orders, and we want to create an input form for that I have selected Create in Scaffold template finally click on Add button.

 

Adding view to controller by right click in asp.net mvc application

 

After adding view here below is a complete View of Index.cshtml which is generated.

 

@model CustomValidationinMVC.Models.Orders

 

@{

ViewBag.Title = "Index";

}

 

<h2>Index</h2>

 

@using (Html.BeginForm()) {

@Html.ValidationSummary(true)

 

<fieldset>

<legend>Orders</legend>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<div class="editor-label">

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

</div>

<div class="editor-field">

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

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

</div>

 

<p>

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

</p>

</fieldset>

}

 

<div>

@Html.ActionLink("Back to List", "Index")

</div>

 

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

}

Now just run the application by entering URL http://localhost:####/order/index to access the page. The output of our custom validations application before entering validate data.

 

Output of our custom validations application before entering validate

 

Output after entering Invalid date (here we entered one day less than the current date and validating using Custom validation we have created and showing error message).

 

Output after entering invalid date in asp.net mvc custom validation application

 

If we select a valid date, our output does not show a custom error message, and it will work as expected.

 

Our output if we selected valid date now it’s not showing custom error message its working fine.

 

This how we will use custom validation with Data Annotation attributes in the asp.net mvc application.