Asp.net-Mvc-3
FluentValidation - 跨多個屬性進行驗證
有一個表單,使用者可以在其中輸入事件的開始日期/時間和結束日期/時間。到目前為止,這是驗證器:
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 - 我該怎麼做?
在我重新閱讀文件後終於讓它工作了:“請注意,Must 還有一個額外的重載,它也接受正在驗證的父對象的實例。”
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 date); } private bool BeAValidTime(string value) { DateTimeOffset offset; return DateTimeOffset.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); } }可能有一種更清潔/更優雅的方式來做到這一點,但現在,它可以工作。