ASP.NET MVC 5 – Customize Model Attribute Validation ( with Client Validation Handling )
Add the Following Item on web.conf to make the Validation with AJAX Effective <appSettings> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> |
JavaScript File Required for Model Vaildation /Scripts/jquery-1.10.2.js /Scripts/jquery.unobtrusive-ajax.js ( NuGet – microsoft.jQuery.Unobtrusive.Ajax ) /Scripts/jquery.validate.min.js ( NuGet – microsoft.jQuery.Unobtrusive.Ajax ) /Scripts/jquery.validate.unobtrusive.min.js ( NuGet – microsoft.jQuery.Unobtrusive.Ajax ) The Validation Function from jQuery / JavaScript File can be executed well from the HEAD Section or from the Page End. |
Model with Validation Annotation public class User { public int ID { get; set; } public string Name { get; set; } public string PostTitle { get; set; } public string Department { get; set; } [PastOnlyAttribute] public DateTime Date { get; set; } } |
Model Validation Attribute Class using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace WebApp.Library { public class PastOnlyAttribute : ValidationAttribute, IClientValidatable { private string ErrorMessage = "The Input Date is later than Today."; public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule(); rule.ValidationType = "dontpasttodaycheck"; /* Only Accept Lower Case */ rule.ErrorMessage = this.ErrorMessage; yield return rule; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DateTime date = Convert.ToDateTime(value); if (date < DateTime.Now) return ValidationResult.Success; else return new ValidationResult(ErrorMessage); } } } |
Controller ActionResult [HttpPost] public ActionResult Form (User user) { if (ModelState.IsValid) { … … } return View(); } |
View <style> .validation { margin: 4px 0px 3px 0px; display: block; color: #770000; cursor: none; font-size: 10pt; font-weight: bold; } </style> @using (Html.BeginForm("Form", "Test")) { @Html.AntiForgeryToken() < div> @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "" } })<br /> @Html.ValidationMessageFor(model => model.Date, "", new { @class = "validation" }) < /div> <input type="submit" value="Submit" /> } |
Reference From My Teammate. Thx