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

  Total Views : 2760
  Comments : 0
 
  Keywords : Asp.net mvc custom validation using validateattribute example, Asp.net mvc custom validation using data annotation attribute,Asp.net mvc custom validation by data annotations attributes

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 now let’s create some custom validation because every business application has their 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 ..) these are default validation provide by MVC if we want you own Custom Validation then we need to inherit from ValidationAttribute and create it.

Create Asp.Net MVC Application

Let’s First create a Basic asp.net Mvc 4 application with name CustomValidationinMVC for that Open visual studio 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 new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# àinside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “CustomValidationinMVC” then finally click on ok button

 

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

 

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

 

select custom basic template in asp.net mvc with example

 

After creating application our project structure like as shown below 

 

custom validations project structure in asp.net mvc with example

 

After creating application now let’s work with Create Model because we are going to use Code first approach of asp.net mvc in this tutorial.

Add New Model to MVC Application

For adding Model just right click on Model folder select Add then inside that select Class in below image you can see the process. 

 

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 class name as “Orders”.

 

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

 

After entering class name click on 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 for that 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 Order class similar way we are going to add another class with name ShippeddateValidate.cs.

 

add new class as model in asp.net mvc folder

 

After entering class name click on 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 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 am going to check date selected by user and against current date if date is less than then we will show error message. After compltion of adding custom logic now 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

{

publicclassOrders

{

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 now let’s create controller.

Add New Controller to MVC Application

For adding Controller Just Right click on Controller Folder inside that select Add and then select Controller.

 

Add controller in asp.net mvc custom validations application

 

After clicking on Controller new dialog will pop up with name Add Controller.

 

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

 

In Template select “Empty MVC controller” and finally click on 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 just right click inside Index ActionResult Method and Select "Add View" to create the view template for our Index form. Here in below snapshot we selected View engine as Razor and we are going to create a strongly type 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 application by entering URL http://localhost:####/order/index to access page. 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 that current date its validating using Custom validation which we have created and showing error message).

 

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

 

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

 

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 asp.net mvc application

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User