如何使用FluentValidation将字符串验证为DateTime

时间:2010-04-01 13:54:17

标签: .net string datetime fluentvalidation fluentvalidation-2.0

使用FluentValidation,是否可以将string验证为可解析的DateTime,而无需指定Custom()代理?

理想情况下,我想说一些类似于EmailAddress的功能,例如:

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

这样的事情:

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

3 个答案:

答案 0 :(得分:25)

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

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

或者你可以写一个custom extension method

答案 1 :(得分:2)

您可以完全按照完成EmailAddress的方式执行此操作。

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

然后

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

    }
}

答案 2 :(得分:1)

如果s.DepartureDateTime已经是DateTime属性;将它验证为DateTime是无稽之谈。 但如果它是一个字符串,Darin的答案是最好的。

要添加的另一件事, 假设您需要将BeAValidDate()方法移动到外部静态类,以便不在每个地方重复相同的方法。如果您选择这样,则需要将Darin的规则修改为:

RuleFor(s => s.DepartureDateTime)
    .Must(d => BeAValidDate(d))
    .WithMessage("Invalid date/time");