문제

와 FluentValidation,그것은 유효성을 검증 string 로 parseable DateTime 를 지정하지 않고 Custom() 대리인?

최고 싶은 같은 말 EmailAddress 함수,예를 들어:

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");

and:

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

or you could write a custom extension method.

다른 팁

당신은 그것을 할 수 있는 정확히 동일한 방법으로는 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();   

    }
}

If s.DepartureDateTime is already a DateTime property; it's nonsense to validate it as DateTime. But if it a string, Darin's answer is the best.

Another thing to add, Suppose that you need to move the BeAValidDate() method to an external static class, in order to not repeat the same method in every place. If you chose so, you'll need to modify Darin's rule to be:

RuleFor(s => s.DepartureDateTime)
    .Must(d => BeAValidDate(d))
    .WithMessage("Invalid date/time");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top