[英]Passing data from the model into custom validation class
I have a data validation class that checks whether the start date of a meeting is before the end date. 我有一个数据验证类,用于检查会议的开始日期是否在结束日期之前。
The model automatically passes in the date that requires validation, but i'm having a bit of difficulty passing the data that it needs to be validated against. 模型会自动传递需要验证的日期,但是我在传递需要验证的数据时遇到了一些困难。
Here's my validation class 这是我的验证课程
sealed public class StartLessThanEndAttribute : ValidationAttribute
{
public DateTime DateEnd { get; set; }
public override bool IsValid(object value)
{
DateTime end = DateEnd;
DateTime date = (DateTime)value;
return (date < end);
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
}
}
Here's the class that contains the data annotations 这是包含数据注释的类
[StartLessThanEnd(ErrorMessage="Start Date must be before the end Date")]
public DateTime DateStart { get; set; }
And here's my controller 这是我的控制器
[HttpPost, Authorize]
public ActionResult Create(Pol_Event pol_Event)
{
ViewData["EventTypes"] = et.GetAllEventTypes().ToList();
StartLessThanEndAttribute startDateLessThanEnd = new StartLessThanEndAttribute();
startDateLessThanEnd.DateEnd = pol_Event.DateEnd;
if (TryUpdateModel(pol_Event))
{
pol_Event.Created_On = DateTime.Now;
pol_Event.Created_By = User.Identity.Name;
eventRepo.Add(pol_Event);
eventRepo.Save();
return RedirectToAction("Details", "Events", new { id = pol_Event.EventID });
}
return View(pol_Event);
}
Validation attributes that work with multiple properties should be applied to the model and not on individual properties: 使用多个属性的验证属性应该应用于模型,而不应用于单个属性:
[AttributeUsage(AttributeTargets.Class)]
public class StartLessThanEndAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var model = (MyModel)value;
return model.StartDate < model.EndDate;
}
}
[StartLessThanEnd(ErrorMessage = "Start Date must be before the end Date")]
public class MyModel
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.