Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 comparing two nullable dates with fluent validation

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

like image 480
Pod Avatar asked Jun 23 '15 09:06

Pod


1 Answers

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);
like image 150
Manoz Avatar answered Dec 19 '22 12:12

Manoz