【问题标题】:FluentValidation Child Validator Message Not ShowingFluentValidation 子验证器消息未显示
【发布时间】:2017-09-17 04:02:19
【问题描述】:

我有以下带有两个构造函数的子验证器,一个没有参数,另一个传递父对象作为参数:

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(x => x.LastName)
            .NotEmpty()
            .WithMessage("Last Name is required");
    }

    public ChildValidator(Parent parent)
    {
        RuleFor(x => x.LastName)
            .Equal(x => parent.LastName)
            .WithMessage("Parent and child Last Name must be equal");
    }
}

父验证器:

public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
        RuleFor(x => x.LastName)
            .NotEmpty()
            .WithMessage("Last Name is required");

        RuleFor(x => x.Children)
            .SetCollectionValidator(parent => new ChildValidator(parent));
    }
}

型号:

[FluentValidation.Attributes.Validator(typeof(ParentValidator))]
public class Parent
{
    public string LastName { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

[FluentValidation.Attributes.Validator(typeof(ChildValidator))]
public class Child
{
    public string LastName { get; set; }

    public int ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

在子部分视图中:

@using (Html.BeginCollectionItem("Children"))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.ParentId)

    @Html.EditorFor(model => model.LastName)
    @Html.ValidationMessageFor(model => model.LastName)

验证工作正常。但是,在显示不带参数的验证器的消息时,不带参数的验证器的消息。

【问题讨论】:

  • 孩子与父母的关系如何?一对多?
  • @PateeGutee 一对多。问题已更新。
  • 你在哪里设置集合验证器?我知道你说有一个用于 Child 的验证器,但你不是还要在 Parent Validator 中指定 Children 使用 Collection Validator 吗?
  • 你也可以添加父验证器吗?
  • @johnny5 问题已更新。

标签: c# asp.net-mvc .net-4.5 fluentvalidation


【解决方案1】:

子视图使用局部视图引起的问题。当你调用@Html.Partial("PartialViewName", model.Children[i]) 时,你会失去 Children[i] 的一部分表达。换句话说,ModelState 包含键 "Children[0].LastName",当您呈现键“LastName”的验证消息时。

您很可能会看到无参数验证器的消息,因为客户端验证在这里有效。但是对于带有参数的验证器,您可以使用自定义逻辑,这可以通过ModelState 工作。

解决方案是将部分视图内容移动到主视图,或使用编辑器模板而不是部分视图:将部分视图移动到 /ControllerName/EditorTemplates/ 文件夹并调用 @Html.EditorFor(m =&gt; m.Children[i], "PartialViewName")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多