添加 child 属性 failure 到 child

Add child property failure to child

我是 FluentValidation 的新手。

我有两个classes

public class A
{
    public B Prop { get; set; }
}

public class B 
{
    public decimal? Example { get; set; }
    public decimal? Example2 { get; set; }
}

而且,我正在尝试在 A class.

中验证 B 属性

如果 Prop 的任何 属性 有验证错误,我想将第一个错误设置为 prop 对象。

我正在尝试这样的。

public class A : AbstractValidator<A>{    
    public A()
    {
        RuleFor(x => x.Prop.Example).NotEmpty();
        RuleFor(x => x.Prop.Example2).NotEmpty();
        RuleFor(x => x.Prop).Custom((obj,context) => {
            if(/* obj.Example or obj.Example2 has validation error */){
                context.AddFailure("message of any Example or Example2 errors");
            }
        });
    }
}

编辑:我的一些观点

<div class="col-12 col-lg-6">
    @Html.LabelFor(x => x.Prop, new { @class = "col-form-label" })
    <div class="input-group mb-3">
        @Html.EditorFor(x => x.Prop.Example, new { htmlAttributes = new { @class = "form-control" } })
        <div class="input-group-append">
            <span class="input-group-text">%</span>
            <span class="input-group-text">@@</span>
        </div>
        @Html.EditorFor(x => x.Prop.Example2, new { htmlAttributes = new { @class = "form-control" } })
        <div class="input-group-append">
            <span class="input-group-text">KVA</span>
        </div>
        <div class="invalid-feedback">@Html.ValidationMessageFor(x => x.Prop)</div>
    </div>
</div>

它应该像这样显示一些

其中左边的输入是Example,右边的是Example 2

所以,如果其中任何一个都失败了,应该可以看到错误消息 (ValidationMessageFor)

我不知道如何验证 Prop 属性 中的错误 RuleFor

这样可以吗?我该怎么做?

我认为您可以使用 FluentValidation 文档为 class B 创建您自己的验证器。 https://fluentvalidation.net/start#creating-your-first-validator

然后在函数的主要范围内,您可以简单地为 class B.

调用该验证器

您可以可能使它正常工作,但您可以通过为 class B 创建一个验证器然后将两个验证消息放入其中来更轻松在彼此相邻的 UI 中:

<div class="col-12 col-lg-6">
    @Html.LabelFor(x => x.Prop, new { @class = "col-form-label" })
    <div class="input-group mb-3">
        @Html.EditorFor(x => x.Prop.Example, new { htmlAttributes = new { @class = "form-control" } })
        <div class="input-group-append">
            <span class="input-group-text">%</span>
            <span class="input-group-text">@@</span>
        </div>
        @Html.EditorFor(x => x.Prop.Example2, new { htmlAttributes = new { @class = "form-control" } })
        <div class="input-group-append">
            <span class="input-group-text">KVA</span>
        </div>
        <div class="invalid-feedback">
            @* Validation messages for both properties of class "B" *@
            @Html.ValidationMessageFor(x => x.Prop.Example)
            @Html.ValidationMessageFor(x => x.Prop.Example2)
        </div>
    </div>
</div>