How to validate a string as DateTime using FluentValidation
Asked Answered
D

3

19

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");
Daylong answered 1/4, 2010 at 13:54 Comment(0)
W
39
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.

Wolsky answered 1/4, 2010 at 13:59 Comment(1)
this is awesome but it will not generate the proper HTML5 validation and will only validate after page submission , is there any way to make the library generate the corresponding html5 ?Steeve
C
4

You can do it exactly the same way that EmailAddress was done.

http://fluentvalidation.codeplex.com/wikipage?title=Custom

public class DateTimeValidator<T> : PropertyValidator
{
    public DateTimeValidator() : base("The value provided is not a valid date") { }

    protected override bool IsValid(PropertyValidatorContext context)
    {
        if (context.PropertyValue == null) return true;

        if (context.PropertyValue as string == null) return false;

        DateTime buffer;
        return DateTime.TryParse(context.PropertyValue as string, out buffer);
    }
}

public static class StaticDateTimeValidator
{
    public static IRuleBuilderOptions<T, TProperty> IsValidDateTime<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder)
    {
        return ruleBuilder.SetValidator(new DateTimeValidator<TProperty>());
    }
}

And then

public class PersonValidator : AbstractValidator<IPerson>
{
    /// <summary>
    /// Initializes a new instance of the <see cref="PersonValidator"/> class.
    /// </summary>
    public PersonValidator()
    {
        RuleFor(person => person.DateOfBirth).IsValidDateTime();   

    }
}
Chymotrypsin answered 20/3, 2014 at 22:16 Comment(0)
C
3

If s.DepartureDateTime is already a DateTime property; it's nonsense to validate it as DateTime. But if it a string, Darin's answer is the best.

Another thing to add, Suppose that you need to move the BeAValidDate() method to an external static class, in order to not repeat the same method in every place. If you chose so, you'll need to modify Darin's rule to be:

RuleFor(s => s.DepartureDateTime)
    .Must(d => BeAValidDate(d))
    .WithMessage("Invalid date/time");
Condescension answered 14/1, 2013 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.