2011-10-09 35 views
26

Có biểu mẫu nơi người dùng có thể nhập ngày/giờ bắt đầu và ngày kết thúc/thời gian cho một sự kiện. Dưới đây là trình xác thực cho đến thời điểm này:FluentValidation - xác thực qua nhiều thuộc tính

Bây giờ tôi cũng muốn thêm xác thực rằng EndDateTime> StartDateTime (kết hợp ngày + thuộc tính thời gian), nhưng không chắc chắn cách thực hiện.

Edit: Để làm rõ, tôi cần phải bằng cách nào đó kết hợp EndDate + EndTime/StartDate + StartTime tức DateTime.Parse (src.StartDate + "" + src.StartTime) và sau đó xác nhận EndDateTime vs StartDateTime - làm thế nào để Tôi làm điều đó?

Trả lời

33

Cuối cùng đã nhận nó làm việc sau khi tôi đọc lại documentation: "Lưu ý rằng có một tình trạng quá tải bổ sung cho Phải mà cũng chấp nhận một thể hiện của đối tượng cha mẹ được xác thực. "

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); 
     } 
    } 

Có thể có cách làm sạch hơn/nhiều hơn để làm điều này, nhưng hiện tại, nó hoạt động.

+0

Có thể làm cùng một phía khách hàng không? – SMC

+0

Điều này không còn hợp lệ nữa trong FluentValitation. Đây là câu trả lời đúng: http://stackoverflow.com/a/20546097/59119 – Natrium

14

Bạn có thể có thể thử bằng cách sử dụng GreaterThan quy tắc:

RuleFor(x => x.EndDate) 
    .GreaterThan(x => x.StartDate) 
    .WithMessage("end date must be after start date"); 
+0

Xin lỗi, bạn chỉ cần thêm phần làm rõ ở trên. Cần kết hợp Date + Time và ** sau đó ** xác nhận – seekay

+0

Có thể thực hiện cùng một phía máy khách không? hoặc vui lòng kiểm tra tại đây http://stackoverflow.com/questions/18142489/how-to-validate-date-in-clientside-using-fluentvalidation – SMC

Các vấn đề liên quan