This article will take you through on how we can implement the Custom Validation using ValidationAttribute in ASP.NET MVC 3.0 Application. In most of the MVC Applications which we develop, apart from the RequiredField validator, we may want to add our Custom Validation as well. As I said, in this article, I had used the ValidationAttribute in MVC for doing the validation on the property. Learn ASP.NET MVC 3.0 Custom Validation using ValidationAttribute
Learn ASP.NET MVC 3.0 Custom Validation using ValidationAttribute
Hi,
In this article we are going to look into how we can have our Custom validation using ValidationAttribute in MVC 3 application. We are going to use the Razor Engine for this article.
We will be using the Data Annotations for achieving the Custom Validation in MVC 3.
I will be taking you through step by step process how you can have you own custom rules and get it implemented on a property in the View. For this article purpose, I will be taking a very simple scenario where user entry will be validated for valid percentage entered ranging from 1 to 100.
Create a new MVC 3 project with Razor View Engine. You can select Internet or Intranet. As we are not going to concentrate on Authentication, it's better to select Intranet Application so it uses Windows Credential.
Add a new directory with the name ValidationRules under the project and a new class file with the name PercentageValidation.cs
Add a reference to System.ComponentModel.DataAnnotations to the project.
We will apply AttributeUsage and we will inherit ValidationAttribute.
You can see the complete implementation of PercentageValidation.cs file below.
using System; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations;
namespace DotnetGurukulMVCUI.ValidationRules { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class PercentageValidation : ValidationAttribute { private int minPercentage = 1; private int maxPercentage = 100;
public PercentageValidation() : base("Percenatge is not valid.") { }
public override bool IsValid(object value) { int percentage = (int)value; if (percentage < this.minPercentage || percentage > this.maxPercentage ) return false; return true; }
} }
If you see the code, we will be specifying the attribute usage. In this case, we had specified, it can be applied on Field or Property. Now we have a constructor and overridden implementation of IsValid where we can have the code for validating the value which will be assigned. Here, I'm checking whether it falls between 1 and 100. I made this validation very simple for easy understanding on how to implement Custom Validation in MVC 3 using ValidationAttribute.
Now we will implement the above attribute in one of our model as given below. The property where we will be using our custom ValidationAttribute is InterestPercentage
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using DotnetGurukulMVCUI.ValidationRules;
namespace DotnetGurukulMVCUI.Models { public class AccountDetails { /// /// Holds the Account Holder Name ///
[Required(ErrorMessage="Name is requried")] public string Name { get; set; } /// /// Holds the Account Type ///
[Required(ErrorMessage = "Account type is requried")] public string AccountType { get; set; } /// /// Holds the Interest Percentage ///
[Required(ErrorMessage = "Percentage is required.")] [PercentageValidation] public int InterestPercentage { get; set; } } }
Now, we will go ahead and design the View (CSHTML file) using the Razor Engine. This will be a simple page we will be using the AccountDetails model which has got only 3 fields with it. The code for .CSHTML file is given in the example as it contains the TABLE tag, it will break the page.
If you look at the CSHTML code, I had specified ValidationMessageFor for each field which I need to validate. The error message will be displayed here.
Modify the HomeController as given below.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DotnetGurukulMVCUI.Models;
namespace DotnetGurukulMVCUI.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); }
/// /// ///
///Holds model with the value ///Control which created the HttpPost. /// [HttpPost] public ActionResult Index(AccountDetails accountDetails, string btnSubmit) { if (ModelState.IsValid) { // Save to DB or do whatever you want to do. } return View(); }
public ActionResult About() { return View(); } } }
After doing these changes, run the application by pressing F5. Try with and without value and submit. Test the Interest Percentage with different values.
This article will provide you a basic idea on how to add validation using ValidationAttribute in MVC 3 Application. Hope it might have provided you a basic knowledge on Custom Validation in MVC 3 Application. You can download this application by downloading the attachment at the end of this article.
See you soon with my next article about MVC 3 Custom Validation at the Client Side.