我使用FluentValidation进行服务器端验证。现在,我想使用must调用一个函数。
这是表单代码片段:
<form method="post"
asp-controller="Category"
asp-action="SaveSpecification"
role="form"
data-ajax="true"
data-ajax-loading="#Progress"
data-ajax-success="Specification_JsMethod">
<input asp-for="Caption" class="form-control" />
<input type="hidden" asp-for="CategoryId" />
<button class="btn btn-primary" type="submit"></button>
</form>我应该对下面的代码进行哪些更改才能调用函数SpecificationMustBeUnique?
public class SpecificationValidator : AbstractValidator<Specification>
{
public SpecificationValidator()
{
RuleFor(x => new { x.CategoryId, x.Caption}).Must(x => SpecificationMustBeUnique(x.CategoryId, x.Caption)).WithMessage("not unique");
}
private bool SpecificationMustBeUnique(int categoryId, string caption)
{
return true / false;
}
} 提示:1- CategoyId和标题的组合应该是唯一的2-提交表单时不进行验证(提交表单时验证不运行)
发布于 2019-08-21 21:42:58
当验证规则应用于不同字段上的值的组合时,棘手的部分是决定应该验证哪个属性。我通常闭上眼睛,指着其中一个视图模型属性说:“这就是我要附加验证器的属性。”用很少的思想。当验证规则应用于单个属性时,FluentValidation工作得最好,因为它知道哪个属性将显示验证消息。
因此,只需选择CategoryId或Caption并将验证器附加到它:
RuleFor(x => x.CategoryId)
.Must(BeUniqueCategoryAndCaption)
.WithMessage("{PropertyName} and Caption must be unique.");BeUniqueCategoryAndCaption方法的签名将如下所示:
private bool BeUniqueCategoryAndCaption(Specification model, int categoryId)
{
return true / false;
}注意:我猜CategoryId属性是一个int,但是您需要确保BeUniqueCategoryAndCaption的categoryId参数与视图模型中的CategoryId属性的类型相同。
https://stackoverflow.com/questions/57591167
复制相似问题