Skip to content

Instantly share code, notes, and snippets.

@djmnz
Last active January 3, 2016 04:49
Show Gist options
  • Save djmnz/8411143 to your computer and use it in GitHub Desktop.
Save djmnz/8411143 to your computer and use it in GitHub Desktop.
Creating a class level validation attribute ASP.Net MVC
[EndDateValidation]
public class CustomDate
{
[DisplayFormat(DataFormatString = "0:dd-MM-yyyy}")]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[Required]
public string Test { get; set; }
}
[AttributeUsage(AttributeTargets.Property|AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class EndDateValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
CustomDate date = value as CustomDate;
return date.EndDate > date.StartDate ? true : false;
}
}
public class CustomDateBinder : DefaultModelBinder
{
//
// GET: /CustomDateBinder/
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
//base.OnModelUpdated(controllerContext, bindingContext);
IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo;
if (errorProvider != null)
{
string errorText = errorProvider.Error;
if (!String.IsNullOrEmpty(errorText))
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorText);
}
}
foreach (ModelValidator validator in bindingContext.ModelMetadata.GetValidators(controllerContext))
{
foreach (ModelValidationResult validationResult in validator.Validate(null))
{
bindingContext.ModelState.AddModelError(CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName), validationResult.Message);
}
}
}
}
public ActionResult TestValidator()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestValidator([ModelBinder(typeof(CustomDateBinder))]CustomDate date)
{
return View();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment