I have a bool along with a nullable DateTime property. The DateTime is only required if the bool is set to true... And I want to validate the date if the bool is true.
I have this expression so far...
When(p => p.HasVisa == true, () => RuleFor(p => p.VisaExpiryDate).NotNull());
Now I try to validate the date in that 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 doesn't allow me to operate on a DateTime that is nullable. How do I do this sort of validation on a nullable date?
Just add ‘When’ to check if the object is not null:
RuleFor(x => x.AlternateNumber)
.Must(IsAllDigits)
.When(x => !string.IsNullOrEmpty(x.AlternateNumber))
.WithMessage("AlternateNumber should contain only digits");
As Joachim mentioned I need to have overloads for BeAValidDate that accepts both null and non-null 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With