gpt4 book ai didi

c# - .Net Fluent Validation 集执行顺序

转载 作者:行者123 更新时间:2023-12-05 01:02:56 26 4
gpt4 key购买 nike

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

但是 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 之前执行。因此 BeAReferenceInSomeTable 验证将在 Id 不存在于表中时抛出异常,而不是由于 ExistsInDatabase 验证而导致验证失败。

首先要解决这个问题,首先想到的是这样的:

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

但是在这种情况下,由于必须在执行之前给出消息,因此我如何设置正确的消息进行验证。

最佳答案

试试这样的:

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

关于c# - .Net Fluent Validation 集执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com