2010-04-01 30 views
8

Với FluentValidation, bạn có thể xác thực string làm phân tích cú pháp DateTime mà không cần chỉ định đại diện Custom() không?Cách xác thực chuỗi là Ngày giờ sử dụng FluentValidation

Lý tưởng nhất, tôi muốn nói điều gì đó giống như chức năng EmailAddress, ví dụ:

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

Vì vậy, một cái gì đó như thế này:

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

Trả lời

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

và:

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

hoặc bạn có thể viết custom extension method.

+0

này là tuyệt vời nhưng nó sẽ không tạo ra các xác nhận HTML5 thích hợp và sẽ chỉ xác nhận sau khi nộp trang, có cách nào để làm cho thư viện tạo ra html5 tương ứng? –

1

Nếu s.DepartureDateTime đã là thuộc tính DateTime; nó là vô nghĩa để xác nhận nó như là DateTime. Nhưng nếu nó là một chuỗi, câu trả lời của Darin là tốt nhất.

Một điều cần thêm, Giả sử bạn cần di chuyển phương thức BeAValidDate() sang lớp tĩnh bên ngoài, để không lặp lại cùng một phương thức ở mọi nơi. Nếu bạn chọn như vậy, bạn sẽ cần phải sửa đổi quy tắc Darin để được:

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

Bạn có thể làm điều đó một cách chính xác cùng một cách mà EmailAddress đã được thực hiện.

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

Và sau đó

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

    } 
} 
Các vấn đề liên quan