.netstringdatetimefluentvalidationfluentvalidation-2.0

How to validate a string as DateTime using FluentValidation


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

Solution

  • 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.