ASP.NET MVC 5 – Customize Model Attribute Validation
public class User { … … [PastOnlyAttribute] public DateTime RegistrationDate { get; set; } } |
[HttpPost] public ActionResult xxx (User user) { if(ModelState.IsValid) <= If Validation is failed, the "ModelState.IsValid" result would be false from here. { … … } } |
using System; using System.ComponentModel.DataAnnotations; namespace WebApp.Library { public class PastOnlyAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { DateTime date = Convert.ToDateTime(value); if (date < DateTime.Now) return ValidationResult.Success; else return new ValidationResult (FormatErrorMessage(validationContext.DisplayName)); } } } |
Reference From My Teammate. Thx