有一个表单,用户可以在其中输入事件的开始日期/时间和结束日期/时间。到目前为止,这是验证器:
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 (组合日期+时间属性)的验证,但不知道如何去做。
编辑: 为了澄清,我需要以某种方式结合 EndDate + EndTime/StartDate + StartTime 即 DateTime.Parse(src.StartDate + " " + src.StartTime) 然后验证 EndDateTime 与 StartDateTime - 我该怎么做?