FluentValidation - Check value is a date only if NOT NULL
This work for me:
RuleFor(user => user.DateOfBirth)
.Must(p=> !(p == DateTime.MinValue))
.WithMessage("DateTime not null");
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;
}
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");