Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 849
Richard Nienaber Avatar asked Apr 01 '10 13:04

Richard Nienaber


3 Answers

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.

like image 63
Darin Dimitrov Avatar answered Nov 05 '22 13:11

Darin Dimitrov


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

    }
}
like image 4
tdbeckett Avatar answered Nov 05 '22 11:11

tdbeckett


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");
like image 3
Mohamed Emad Avatar answered Nov 05 '22 12:11

Mohamed Emad