2010-04-01 12 views
8

Przy FluentValidation, czy możliwe jest sprawdzenie poprawności string jako parsowania DateTime bez konieczności podawania delegata Custom()?Jak sprawdzić łańcuch jako DateTime przy użyciu FluentValidation

Idealnie, chciałbym powiedzieć coś takiego funkcji EMAILADDRESS, np

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

Więc coś takiego:

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

Odpowiedz

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

oraz:

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

lub możesz napisać custom extension method.

+0

to jest niesamowite, ale to nie będzie generować odpowiednią walidację HTML5 i zweryfikuje dopiero po poddaniu strony, czy jest jakiś sposób, aby biblioteka generowania odpowiadający html5? –

1

Jeśli s.DepartureDateTime jest już właściwością DateTime; nie ma sensu, aby potwierdzić go jako DateTime. Ale jeśli jest to ciąg znaków, odpowiedź Darina jest najlepsza.

Kolejna rzecz do dodania, Załóżmy, że musisz przenieść metodę BeAValidDate() na zewnętrzną klasę statyczną, aby nie powtarzać tej samej metody w każdym miejscu. Jeśli wybierzesz tak, trzeba zmodyfikować regułę Darin być:

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

Można to zrobić dokładnie tak samo, EmailAddress zostało zrobione.

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

A potem

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

    } 
} 
Powiązane problemy