1

我正在使用 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 和 Caption 的组合应该是唯一的 2 - 提交表单时没有进行验证(提交表单时没有进行验证)

4

1 回答 1

1

棘手的部分是决定当验证规则应用于不同字段上的值组合时应该验证哪个属性。我通常只是闭上眼睛,指向视图模型属性之一并说“这是我将附加验证器的属性”。很少考虑。当验证规则应用于单个属性时,FluentValidation 效果最佳,因此它知道哪个属性将显示验证消息。

因此,只需选择CategoryIdCaption将验证器附加到它:

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

于 2019-08-21T13:42:58.233 回答