How to validate a string as DateTime using FluentValidation

Richard Nienaber picture Richard Nienaber · Apr 1, 2010 · Viewed 13.4k times · Source

With FluentValidation, is it possible to validate a string as a parseable DateTime without having to specify a Custom() delegate?

Ideally, I'd like to say something like the EmailAddress function, e.g.:

RuleFor(s => s.EmailAddress).EmailAddress().WithMessage("Invalid email address");

So something like this:

RuleFor(s => s.DepartureDateTime).DateTime().WithMessage("Invalid date/time");

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 1, 2010
RuleFor(s => s.DepartureDateTime)
    .Must(BeAValidDate)
    .WithMessage("Invalid date/time");

and:

private bool BeAValidDate(string value)
{
    DateTime date;
    return DateTime.TryParse(value, out date);
}

or you could write a custom extension method.