2010-04-01 34 views
8

使用FluentValidation,是否可以驗證string爲可解析DateTime而無需指定Custom()委託?如何使用FluentValidation驗證字符串爲DateTime

理想情況下,我想這樣說的EmailAddress的功能,如:

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

因此,像這樣:

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

回答

21
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

+0

這是真棒,但它不會產生正確的HTML5驗證和頁面提交後纔會生效,有沒有什麼辦法讓庫生成對應的html5? – 2014-06-16 08:26:00

1

如果s.DepartureDateTime已經是一個DateTime財產;驗證它爲DateTime是無稽之談。 但是,如果它是一個字符串,Darin的答案是最好的。

要添加的另一件事, 假設您需要將BeAValidDate()方法移動到外部靜態類,以便不在每個地方重複相同的方法。如果你選擇這樣做,你需要修改Darin的規則:

RuleFor(s => s.DepartureDateTime) 
    .Must(d => BeAValidDate(d)) 
    .WithMessage("Invalid date/time"); 
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(); 

    } 
}