【问题标题】:using must in fluentValidation在 fluentValidation 中使用必须
【发布时间】:2019-08-21 12:02:01
【问题描述】:

我正在使用 FluentValidation 进行服务器端验证。现在我想使用 must 调用一个函数。

这是表单代码sn-p:

<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 - 提交表单时未完成验证(提交表单时验证未运行)

【问题讨论】:

  • CategoryId 和 Caption 的组合是否应该是唯一的?您是否收到异常或编译器错误?提交表单时验证是否未运行?目前尚不清楚您需要解决什么问题。
  • 见官方文档中的Predicate Validator
  • 提示:1 - CategoyId 和 Caption 的组合应该是唯一的 2 - 提交表单时不做验证

标签: fluentvalidation fluentvalidation-2.0


【解决方案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 属性类型相同。

【讨论】:

  • 但是,BeUniqueCategoryAndCaption 没有运行!但是,值(cpation和categoryId)被传递给模型
  • @farshidazizi:你在 FluentValidation 类中使用RuleFor(x =&gt; x.CategoryId) 吗?如果您是,请在您的控制器中发布代码,以及您如何将 FluentValidation 与 Web 框架(MVC、WebForms 等)集成。
  • @GregBurghardt:是的,我在我的 FluentValidation 类/中使用 RuleFor(x => x.CategoryId) 并使用 mvc 核心
  • @farshidazizi:是否还有其他 FluentValidation 规则正在运行,只有这一条没有?请在您的控制器中发布代码,以及将 MVC Core 配置为使用 FluentValidation 的代码。另外,请发布您如何将Specification 视图模型与验证器相关联。在这一点上,感觉 MVC 框架和 FluentValidation 之间的“胶水”没有正常工作。
猜你喜欢
  • 2015-04-16
  • 2022-06-16
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多