-->

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

Introduction

In this post, How to implement Custom user defined Age Range 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 Age Range 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 AgeRangeValidation : ValidationAttribute, IClientValidatable
  2. {
  3.  
  4. public int MinAge { get; set; }
  5. public int MaxAge { get; set; }
  6.  
  7. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  8. {
  9. //THIS IS FOR SERVER SIDE VALIDATION
  10.  
  11. // if value not supplied then no error return
  12. if (value == null)
  13. {
  14. return null;
  15. }
  16.  
  17. int age = 0;
  18. age = DateTime.Now.Year - Convert.ToDateTime(value).Year;
  19. if (age >= MinAge && age <= MaxAge)
  20. {
  21. return null; // Validation success
  22. }
  23. else
  24. {
  25. return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  26. // error
  27. }
  28. }
  29.  
  30. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  31. {
  32. //THIS IS FOR SET VALIDATION RULES CLIENT SIDE
  33.  
  34. var rule = new ModelClientValidationRule()
  35. {
  36. ValidationType = "agerangevalidation",
  37. ErrorMessage = FormatErrorMessage(metadata.DisplayName)
  38. };
  39.  
  40. rule.ValidationParameters["minage"] = MinAge;
  41. rule.ValidationParameters["maxage"] = MaxAge;
  42. yield return rule;
  43. }
  44. }

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 I will add code for client side validation for our custom validation (age range validation)
  2.  
  3. $.validator.unobtrusive.adapters.add("agerangevalidation", ["minage", "maxage"], function (options) {
  4. options.rules["agerangevalidation"] = options.params;
  5. options.messages["agerangevalidation"] = options.message;
  6. });
  7.  
  8. $.validator.addMethod("agerangevalidation", function (value, elements, params) {
  9. if (value) {
  10. var valDate = new Date(value);
  11. if ((new Date().getFullYear() - valDate.getFullYear()) < parseInt(params.minage) ||
  12. (new Date().getFullYear() - valDate.getFullYear()) > parseInt(params.maxage)
  13. ) {
  14. return false;
  15. //validation failed
  16. }
  17. }
  18. return true;
  19. });

Step-7: Apply validation on model.

Open your model and add validation. Please follow below code

  1. public partial class Registration
  2. {
  3. public int ID { get; set; }
  4. [Required(ErrorMessage="Full name required", AllowEmptyStrings=false)]
  5. public string FullName { get; set; }
  6. [Required(ErrorMessage="Username required", AllowEmptyStrings=false)]
  7. public string Username { get; set; }
  8. [Required(ErrorMessage="Password required", AllowEmptyStrings=false)]
  9. [DataType( System.ComponentModel.DataAnnotations.DataType.Password)]
  10. public string Password { get; set; }
  11.  
  12. [Required(ErrorMessage="DOB Required", AllowEmptyStrings=false)]
  13. [DataType( System.ComponentModel.DataAnnotations.DataType.Date)]
  14. [DisplayFormat(DataFormatString="{0:dd-MM-yyyy}")]
  15. //Here I am going to add our custom validation (Age Range validation)
  16. [AgeRangeValidation(ErrorMessage="Age must be between 18 - 30", MinAge=18, MaxAge=30)]
  17. public System.DateTime DOB { get; set; }
  18. }

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 "form" Action with Model Parameter (here "Registration") into "Registration" 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: