.Net Fluent Validation设置执行顺序

时间:2014-06-12 11:11:32

标签: c# .net validation

我需要设置验证的执行顺序,以便在第一次失败后停止验证。

然而this is not available,所以我想知道还有其他方法可以做到这一点。

通常情况下我会这样:

public Constructor(){

    // Simple validation
    RuleFor(x => x.Id).NotNull().NotEmpty();

    // advanced validation
    // item must exist in database
    RuleFor(x => x.Id).Must(ExistsInDatabase);

    // item must exist in database previously
    // item must be some of the allowed names -- fetched from db
    RuleFor(x => x.Id).Must(BeAReferenceInSomeTable);

    private bool ExistsInDatabase(){}

    private bool BeAReferenceInSomeTable(){}

}

但是这个BeAReferenceInSomeTable可以在ExistsInDatabase之前执行。 因此,当表中不存在Id而不是由于ExistsInDatabase验证而验证失败时,BeAReferenceInSomeTable验证将抛出异常。

为了解决这个问题首先想到的是:

public Constructor(){

    CascadeMode = FluentValidation.CascadeMode.StopOnFirstFailure;

    // simple validation stays the same
    ...

    // advanced validation
    RuleFor(x => x.Id)
        .Must(ExistsInDatabase)
        .Must(BeAReferenceInSomeTable)
        .When(x => !string.IsNullOrEmpty(x.Id) &&
                    !string.IsNullOrEmpty(x.Name)
        );  
}

但是在这种情况下,我如何设置一个propper消息进行验证,因为必须在执行之前给出消息。

1 个答案:

答案 0 :(得分:4)

尝试这样的事情:

public Constructor(){

    // Simple validation
    RuleFor(x => x.Id).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Must not be null");

    RuleFor(x => x.Id).NotEmpty().WithMessage("Must not be empty");


    // advanced validation
    // item must exist in database
    RuleFor(x => x.Id).Must(ExistsInDatabase).WithMessage("Must exist in database");

    // item must exist in database previously
    // item must be some of the allowed names -- fetched from db
    RuleFor(x => x.Id).Must(BeAReferenceInSomeTable).WithMessage("Must not be referenced");

    private bool ExistsInDatabase(){}

    private bool BeAReferenceInSomeTable(){}

}

并为执行顺序锁定:

RuleFor(x => x.Id).Cascade(CascadeMode.StopOnFirstFailure)
    .NotNull().WithMessage("Must not be null")
    .NotEmpty().WithMessage("Must not be empty")
    .Must(ExistsInDatabase).WithMessage("Must exist in database")
    .Must(BeAReferenceInSomeTable).WithMessage("Must not be referenced");