Question

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?

Was it helpful?

Solution 2

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;
}

OTHER TIPS

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

This work for me:

RuleFor(user => user.DateOfBirth)
  .Must(p=> !(p == DateTime.MinValue))
  .WithMessage("DateTime not null");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top