FluentValidation - Check value is a date only if NOT NULL

I have a bool along with a null DateTime property. DateTime is only required if bool is set to true ... And I want to check the date if bool is true.

I have this expression so far ...

When(p => p.HasVisa == true, () => RuleFor(p => p.VisaExpiryDate).NotNull()); 

Now I'm trying to check the date in this expression using the .Must extension and my custom BeAValidDate method ...

 When(p => p.HasVisa == true, () => RuleFor(p => p.VisaExpiryDate).NotNull().Must(BeAValidDate)); private bool BeAValidDate(DateTime date) { if (date == default(DateTime)) return false; return true; } 

But the .Must extension does not allow me to work with DateTime, which is null. How can I perform such a check on a zero date?

thanks

+9
source share
3 answers

As Joachim mentioned, I need to have overloads for BeAValidDate that accept both null and non-zero dates.

 private bool BeAValidDate(DateTime date) { if (date == default(DateTime)) return false; return true; } private bool BeAValidDate(DateTime? date) { if (date == default(DateTime)) return false; return true; } 
0
source

Just add 'When to check if an object is null:

 RuleFor(x => x.AlternateNumber) .Must(IsAllDigits) .When(x => !string.IsNullOrEmpty(x.AlternateNumber)) .WithMessage("AlternateNumber should contain only digits"); 
+20
source

this work is for me.

RuleFor (user => user.DateOfBirth) .Must (p =>! (P == DateTime.MinValue)). WithMessage ("DateTime not null");

+1
source

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


All Articles