Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation - Check value is a date only if NOT NULL

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?

like image 457
Greg Quinn Avatar asked May 25 '13 06:05

Greg Quinn


2 Answers

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");
like image 104
Sagar Nanivadekar Avatar answered Nov 14 '22 03:11

Sagar Nanivadekar


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;
}
like image 2
Greg Quinn Avatar answered Nov 14 '22 03:11

Greg Quinn