-->

How to implement Custom user defined Validation / Data Annotations rules in MVC 4 application.

Introduction

In this post, how to implement Custom user defined Validation / Data Annotations rules in MVC 4 application.
There are many validation attributes available in MVC 4 like required, StringLength, Range, RegularExpression and more but sometimes we may require specific type of validation. In this article, I will explain how you can create your own custom validation attribute for validation minimum age and also how to make it work on client side as well.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for save  data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a new class for create custom validation rule.

write the following code in this class.
We need to import following namespace
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Web.Mvc;
  1. public class AgeValidation : ValidationAttribute, IClientValidatable
  2. {
  3. public int MinimumAge { get; set; }
  4. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  5. {
  6. // here this code is for validation on server side, validate when Model.IsValid called
  7. if (value == null)
  8. {
  9. return null;
  10. }
  11. int currentAge = DateTime.Now.Year - ((DateTime)value).Year;
  12. if (currentAge >= MinimumAge)
  13. {
  14. return null; //validation success
  15. }
  16. else
  17. {
  18. return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  19. }
  20.  
  21. }
  22. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  23. {
  24. //Here we will set validation rule for client side validation
  25. var rule = new ModelClientValidationRule
  26. {
  27. ErrorMessage = FormatErrorMessage(metadata.DisplayName),
  28. ValidationType = "minagevalidation" // must be all in lower case, spacial char not allowed in the validation type name
  29. };
  30. rule.ValidationParameters["minage"] = MinimumAge;
  31. yield return rule;
  32. }
  33. }

Step-6: Add a new js file for apply custom validation rule client side.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > new item > select javascript file > Enter file name > Add.

write the following code in this js file.

  1. // here we will add validation for client side validation of our custom validation
  2. $.validator.unobtrusive.adapters.addSingleVal("minagevalidation", "minage");
  3. $.validator.addMethod("minagevalidation", function (value, element, param) {
  4. if (value) {
  5. var date = new Date(value);
  6. var currentAge = new Date().getFullYear() - date.getFullYear();
  7. if (currentAge < parseInt(param)) {
  8. return false;
  9. }
  10. }
  11. return true;
  12. });

Step-7: Apply validation on model.

Open your model and add validation. Please follow below code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. public partial class Registration
  5. {
  6. public int ID { get; set; }
  7. [Required(ErrorMessage="Full Name required!", AllowEmptyStrings=false)]
  8. public string FullName { get; set; }
  9. [Required(ErrorMessage = "Username required!", AllowEmptyStrings = false)]
  10. public string Username { get; set; }
  11. [Required(ErrorMessage = "Password required!", AllowEmptyStrings = false)]
  12. [DataType(dataType: DataType.Password)]
  13. public string Password { get; set; }
  14. [Required(ErrorMessage = "Date of Birth required!", AllowEmptyStrings = false)]
  15. [AgeValidation(ErrorMessage="Age must be greater then or equal to 18", MinimumAge=18)]
  16. public System.DateTime DOB { get; set; }
  17. }

Step-8: Add a new Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Step-9: Add new action into your controller for Get Method

Here I have added "form" Action into "Registration" Controller. Please write this following code

  1. public class RegistrationController : Controller
  2. {
  3. public ActionResult form()
  4. {
  5. return View();
  6. }
  7. }

Step-10: Add view for this Action & design.

Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Add.
HTML Code
  1. @model MVCCustomValidation.Registration
  2. @{
  3. ViewBag.Title = "form";
  4. }
  5. <h2>form</h2>
  6.  
  7. @using (Html.BeginForm()) {
  8. @Html.ValidationSummary(true)
  9. if (ViewBag.Message !=null)
  10. {
  11. <div style="padding:5px; width:300px;color:red; border:1px solid green">
  12. @ViewBag.Message
  13. </div>
  14. }
  15. <fieldset>
  16. <legend>Registration</legend>
  17.  
  18. <div class="editor-label">
  19. @Html.LabelFor(model => model.FullName)
  20. </div>
  21. <div class="editor-field">
  22. @Html.EditorFor(model => model.FullName)
  23. @Html.ValidationMessageFor(model => model.FullName)
  24. </div>
  25.  
  26. <div class="editor-label">
  27. @Html.LabelFor(model => model.Username)
  28. </div>
  29. <div class="editor-field">
  30. @Html.EditorFor(model => model.Username)
  31. @Html.ValidationMessageFor(model => model.Username)
  32. </div>
  33.  
  34. <div class="editor-label">
  35. @Html.LabelFor(model => model.Password)
  36. </div>
  37. <div class="editor-field">
  38. @Html.EditorFor(model => model.Password)
  39. @Html.ValidationMessageFor(model => model.Password)
  40. </div>
  41.  
  42. <div class="editor-label">
  43. @Html.LabelFor(model => model.DOB)
  44. </div>
  45. <div class="editor-field">
  46. @Html.EditorFor(model => model.DOB)
  47. @Html.ValidationMessageFor(model => model.DOB)
  48. </div>
  49.  
  50. <p>
  51. <input type="submit" value="Create" />
  52. </p>
  53. </fieldset>
  54. }
  55.  
  56. <div>
  57. @Html.ActionLink("Back to List", "Index")
  58. </div>
  59.  
  60. @section Scripts {
  61. @Scripts.Render("~/bundles/jqueryval")
  62. @* Need to add our custom validation js here *@
  63. <script src="~/Scripts/MyCustomValidation.js"></script>
  64. }

Step-11: Add new action into your controller for POST Method (for form)

Here I have added "Login" Action with Model Parameter (here "User") into "Home" Controller. Please write this following code

  1. [HttpPost]
  2. public ActionResult form(Registration r)
  3. {
  4. if (ModelState.IsValid)
  5. {
  6. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  7. {
  8. dc.Registrations.Add(r);
  9. dc.SaveChanges();
  10. ModelState.Clear();
  11. r = null;
  12. ViewBag.Message = "Success!";
  13. }
  14. }
  15. else
  16. {
  17. ViewBag.Message = "Failed!";
  18. }
  19. return View(r);
  20. }

Step-12: Run Application.


Download Application     Live Demo




Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: