MVC5 comparing two nullable dates with fluent validation

大兔子大兔子 提交于 2020-01-16 03:52:01

问题


How can I write a rule in fluent validation to check two nullable dates in that the start date needs to be earlier than the end date.

I am thinking along the line of

RuleFor(c => c.StartDate)
            .NotEmpty()

if the start date is not empty and end date not empty then compare


回答1:


Something like this-

RuleFor(ac => ac.StartDate)
     .NotEmpty().WithMessage("*Required")

 RuleFor(ac => ac.EndDate)
     .NotEmpty().WithMessage("*Required")
     .GreaterThan(r => r.StartDate);

Note-

The datatypes must be same for comparison.

Or more convinient from this source-

 RuleFor(m => m.StartDate)
            .NotEmpty()
            .WithMessage("Start Date is Required");

        RuleFor(m => m.EndDate)
            .NotEmpty().WithMessage("End date is required")
            .GreaterThan(m => m.StartDate.Value)
                            .WithMessage("End date must after Start date")
            .When(m => m.StartDate.HasValue);


来源:https://stackoverflow.com/questions/30998626/mvc5-comparing-two-nullable-dates-with-fluent-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!