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

19

使用FluentValidation,是否可以验证可解析为DateTimestring,而无需指定Custom()委托?

理想情况下,我希望像EmailAddress函数那样说话,例如:

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

所以像这样:

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

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

并且:

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

或者你可以编写一个自定义扩展方法


这很棒,但它不会生成正确的HTML5验证,并且只能在页面提交后进行验证,有没有办法使库生成相应的HTML5? - Mohamad Alhamoud

4
您可以以与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();   

    }
}

3

如果 s.DepartureDateTime 已经是一个 DateTime 属性,那么将其作为 DateTime 进行验证就没有意义了。 但是如果它是一个字符串,则 Darin 的答案是最好的。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接