使用FluentValidation,是能够验证一个string作为可解析DateTime而不必指定一个Custom()代表?

在理想情况下,我想这样说的EmailAddress的功能,e.g:

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

因此,像这样:

RuleFor(s => s.DepartureDateTime).DateTime().WithMessage("Invalid date/time");
有帮助吗?

解决方案

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

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

或可以编写自定义扩展方法

其他提示

您可以做完全一样的方式,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();   

    }
}

如果s.DepartureDateTime已经是一个日期时间属性;这是废话,以验证它为日期时间。 但是,如果一个字符串,达林的回答是最好的。

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

RuleFor(s => s.DepartureDateTime)
    .Must(d => BeAValidDate(d))
    .WithMessage("Invalid date/time");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top