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 > OKStep-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
- using System.ComponentModel.DataAnnotations;
- using System.Web.Mvc;
- public class AgeRangeValidation : ValidationAttribute, IClientValidatable
- {
- public int MinAge { get; set; }
- public int MaxAge { get; set; }
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- //THIS IS FOR SERVER SIDE VALIDATION
- // if value not supplied then no error return
- if (value == null)
- {
- return null;
- }
- int age = 0;
- age = DateTime.Now.Year - Convert.ToDateTime(value).Year;
- if (age >= MinAge && age <= MaxAge)
- {
- return null; // Validation success
- }
- else
- {
- return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
- // error
- }
- }
- public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
- {
- //THIS IS FOR SET VALIDATION RULES CLIENT SIDE
- var rule = new ModelClientValidationRule()
- {
- ValidationType = "agerangevalidation",
- ErrorMessage = FormatErrorMessage(metadata.DisplayName)
- };
- rule.ValidationParameters["minage"] = MinAge;
- rule.ValidationParameters["maxage"] = MaxAge;
- yield return rule;
- }
- }
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.
- // Here I will add code for client side validation for our custom validation (age range validation)
- $.validator.unobtrusive.adapters.add("agerangevalidation", ["minage", "maxage"], function (options) {
- options.rules["agerangevalidation"] = options.params;
- options.messages["agerangevalidation"] = options.message;
- });
- $.validator.addMethod("agerangevalidation", function (value, elements, params) {
- if (value) {
- var valDate = new Date(value);
- if ((new Date().getFullYear() - valDate.getFullYear()) < parseInt(params.minage) ||
- (new Date().getFullYear() - valDate.getFullYear()) > parseInt(params.maxage)
- ) {
- return false;
- //validation failed
- }
- }
- return true;
- });
Step-7: Apply validation on model.
Open your model and add validation. Please follow below code
- public partial class Registration
- {
- public int ID { get; set; }
- [Required(ErrorMessage="Full name required", AllowEmptyStrings=false)]
- public string FullName { get; set; }
- [Required(ErrorMessage="Username required", AllowEmptyStrings=false)]
- public string Username { get; set; }
- [Required(ErrorMessage="Password required", AllowEmptyStrings=false)]
- [DataType( System.ComponentModel.DataAnnotations.DataType.Password)]
- public string Password { get; set; }
- [Required(ErrorMessage="DOB Required", AllowEmptyStrings=false)]
- [DataType( System.ComponentModel.DataAnnotations.DataType.Date)]
- [DisplayFormat(DataFormatString="{0:dd-MM-yyyy}")]
- //Here I am going to add our custom validation (Age Range validation)
- [AgeRangeValidation(ErrorMessage="Age must be between 18 - 30", MinAge=18, MaxAge=30)]
- public System.DateTime DOB { get; set; }
- }
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
- public class RegistrationController : Controller
- {
- public ActionResult form()
- {
- return View();
- }
- }
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
- @model MVCCustomValidation.Registration
- @{
- ViewBag.Title = "form";
- }
- <h2>form</h2>
- @using (Html.BeginForm()) {
- @Html.ValidationSummary(true)
- if (ViewBag.Message !=null)
- {
- <div style="padding:5px; width:300px;color:red; border:1px solid green">
- @ViewBag.Message
- </div>
- }
- <fieldset>
- <legend>Registration</legend>
- <div class="editor-label">
- @Html.LabelFor(model => model.FullName)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.FullName)
- @Html.ValidationMessageFor(model => model.FullName)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.Username)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.Username)
- @Html.ValidationMessageFor(model => model.Username)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.Password)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.Password)
- @Html.ValidationMessageFor(model => model.Password)
- </div>
- <div class="editor-label">
- @Html.LabelFor(model => model.DOB)
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.DOB)
- @Html.ValidationMessageFor(model => model.DOB)
- </div>
- <p>
- <input type="submit" value="Create" />
- </p>
- </fieldset>
- }
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- @* Need to add our custom validation js here *@
- <script src="~/Scripts/MyCustomValidation.js"></script>
- }
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
- [HttpPost]
- public ActionResult form(Registration r)
- {
- if (ModelState.IsValid)
- {
- using (MyDatabaseEntities dc = new MyDatabaseEntities())
- {
- dc.Registrations.Add(r);
- dc.SaveChanges();
- ModelState.Clear();
- r = null;
- ViewBag.Message = "Success!";
- }
- }
- else
- {
- ViewBag.Message = "Failed!";
- }
- return View(r);
- }
Step-12: Run Application.
Download Application Live Demo
- How to implement Custom user defined Validation / Data Annotations rules in MVC 4 application.
- How to implement Custom user defined At Least One required Validation rules in MVC 4 application.