Search code examples
c#fluentfluentvalidation

FluentValidation when does not raises any message


I have a problem with this code:

RuleFor(field => field.TermEndDate)
    .NotEmpty()
    .When(x => x.TermEndDate == x.TermStartDate)
    .WithMessage("error...");

I set TermEndDate = DateTime.Now but no message raises!

My test code is:

var now = DateTime.Now;
var command = new AddTermCommand
{
    SchoolId = Guid.NewGuid(),
    TermStartDate = now,
    TermEndDate = now
};
var cmd = command.Validate();
if (!cmd.IsValid)
    Console.WriteLine(cmd.Errors.First().ErrorMessage);

Solution

  • There are two problems with your code:

    As I noted in the comments, the first problem is that you cannot really compare with DateTime.Now since calling DateTime.Now after some time (even very small) gives you a different value.

    The second problem is that you are using the When method. The When method is used to specify a condition to run the validation in the first place (for example, you can specify that you want to validate this property only if the value of some other property is 1), it cannot be used to specify a validation rule. Instead you can use the Must method like this:

    RuleFor(field => field.TermEndDate)
        .NotEmpty()
        .Must(x => (DateTime.Now - x).Duration() > TimeSpan.FromMinutes(1))
        .WithMessage("error...");
    

    Here I am using Must to say that the value of TermEndDate should be at least 1 minute more or less (1 minute away from DateTime.Now) than the time when I run the validation (which is when I invoke Validate).

    UPDATE:

    To compare TermEndDate with TermStartDate, you can do it like this:

    RuleFor(field => field.TermEndDate)
        .Must((cmd, enddate) => enddate != cmd.TermStartDate)
        .WithMessage("error...");