20

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?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Greg Quinn
  • 1,927
  • 1
  • 23
  • 26

3 Answers3

30

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");
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • 1
    I know this is not the case, but for those cases in which you have more rules to set, you can use the DependentRules method – ndarriulat Aug 27 '19 at 14:14
3

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;
}
Greg Quinn
  • 1,927
  • 1
  • 23
  • 26
2

This work for me:

RuleFor(user => user.DateOfBirth)
  .Must(p=> !(p == DateTime.MinValue))
  .WithMessage("DateTime not null");
FortyTwo
  • 2,414
  • 3
  • 22
  • 33