asp.net-mvc-3 – FluentValidation – 验证跨多个属性
发布时间:2020-05-23 11:27:08 所属栏目:asp.Net 来源:互联网
导读:有一个用户可以输入事件的开始日期/时间和结束日期/时间的表单。到目前为止,这是验证器: public class EventModelValidator : AbstractValidatorEventViewModel { public EventModelValidator() { RuleFor(x = x.StartDa
|
有一个用户可以输入事件的开始日期/时间和结束日期/时间的表单。到目前为止,这是验证器: public class EventModelValidator : AbstractValidator<EventViewModel>
{
public EventModelValidator()
{
RuleFor(x => x.StartDate)
.NotEmpty().WithMessage("Date is required!")
.Must(BeAValidDate).WithMessage("Invalid date");
RuleFor(x => x.StartTime)
.NotEmpty().WithMessage("Start time is required!")
.Must(BeAValidTime).WithMessage("Invalid Start time");
RuleFor(x => x.EndTime)
.NotEmpty().WithMessage("End time is required!")
.Must(BeAValidTime).WithMessage("Invalid End time");
RuleFor(x => x.Title).NotEmpty().WithMessage("A title is required!");
}
private bool BeAValidDate(string value)
{
DateTime date;
return DateTime.TryParse(value,out date);
}
private bool BeAValidTime(string value)
{
DateTimeOffset offset;
return DateTimeOffset.TryParse(value,out offset);
}
}
现在我还要添加验证,EndDateTime> StartDateTime(组合日期时间属性),但不知道如何去做。 编辑: 解决方法在我重新读取 documentation后,最后让它工作:“请注意,对于”必须“还有一个额外的重载也可以接受正在验证的父对象的一个实例。public class EventModelValidator : AbstractValidator<EventViewModel>
{
public EventModelValidator()
{
RuleFor(x => x.StartDate)
.NotEmpty().WithMessage("Date is required!")
.Must(BeAValidDate).WithMessage("Invalid date");
RuleFor(x => x.StartTime)
.NotEmpty().WithMessage("Start time is required!")
.Must(BeAValidTime).WithMessage("Invalid Start time");
RuleFor(x => x.EndTime)
.NotEmpty().WithMessage("End time is required!")
.Must(BeAValidTime).WithMessage("Invalid End time")
// new
.Must(BeGreaterThan).WithMessage("End time needs to be greater than start time");
RuleFor(x => x.Title).NotEmpty().WithMessage("A title is required!");
}
private bool BeAValidDate(string value)
{
DateTime date;
return DateTime.TryParse(value,out offset);
}
// new
private bool BeGreaterThan(EventViewModel instance,string endTime)
{
DateTime start = DateTime.Parse(instance.StartDate + " " + instance.StartTime);
DateTime end = DateTime.Parse(instance.EndDate + " " + instance.EndTime);
return (DateTime.Compare(start,end) <= 0);
}
}
这可能是一个更清洁/更有条理的方法,但现在它可以工作。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 如何更改ASP.NET MVC中的默认验证错误消息?
- asp.net-mvc – Asp.net MVC TextArea
- 如何在ASP.NET中阻止IP地址或IP类
- asp.net-mvc-4 – 如何在ASP.NET MVC中使用React
- asp.net – 存储Web应用程序项目组合参考的位置?
- asp.net-mvc – 实体框架包含OrderBy随机生成重复数据
- ASP.NET MVC中引用JavaScript的正确方法?
- asp.net – 错误:远程服务器返回错误:(401)未经授权
- asp.net-mvc – 为一个MVC视图使用两个强类型模型
- 缺少ASP.NET 5模板
推荐文章
站长推荐
热点阅读
