FluentValidation when not causing 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 the message does not go up!

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); 
+5
source share
2 answers

There are two problems in the code:

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

The second problem is that you are using the When method. The When method is used to specify the conditions for starting a check first (for example, you can specify that you want to check this property only if the value of some other property is 1), it cannot be used to specify a check rule. Instead, you can use the Must method as follows:

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

Here I use Must to say that the value of TermEndDate should be at least 1 minute more or less (1 minute from DateTime.Now ) than the time when I run the check (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..."); 
+3
source

Your rule will never fire, because TermEndDate will never equal DateTime.Now ; you are comparing the value from the past with the moving value of Now .

Try checking for a specific date, or just for a day:

 RuleFor(field => field.TermEndDate) .NotEmpty() .When(x => x.TermEndDate.Date == DateTime.Today) .WithMessage("error..."); 
+2
source

Source: https://habr.com/ru/post/1239577/


All Articles