FluentValidation - Check value is a date only if NOT NULL

Greg Quinn picture Greg Quinn · May 25, 2013 · Viewed 14k times · Source

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?

Thanks

Answer

Sagar Nanivadekar picture Sagar Nanivadekar · Aug 25, 2016

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");