我正在尝试在 Blazor 模型中进行儿童 Fluent 验证,但效果不佳

问题描述 投票:0回答:0

我正在为我在 blazor 项目中的课程做 FluentValidation。 模型和验证类如下所示。

public class A{
public string  Afield1 { get; set; }
public string  Afield2 { get; set; }
public List<B> Bs { get; set; } 

}

public class B{
public string  Bfield1 { get; set; }
public string  Bfield2 { get; set; }

}


public class AValidator : AbstractValidator<A>
{
        public AValidator()
        {
         RuleFor(s => s.Afield1).NotEmpty().WithMessage("Select The Afield1");
         RuleForEach(s => s.Bs).SetValidator(new BValidator());
        }
}

public class BValidator : AbstractValidator<B>
{
        public BValidator()
        {
            RuleFor(s => s.Bfield1).NotEmpty().WithMessage("Select Bfield1");
          
        }
}

我想做一些复杂的验证。
如果 A 中的 Afield2 的值为 "KI" ,那么我只想为 B

的 Bfield2 设置验证消息

我试过下面的代码不起作用

 RuleFor(s => s.Bs).Custom((c, e) => 
        {
            if (e.InstanceToValidate.Afield2 == "KI")
            {
                if (c.Any(a=>string.IsNullOrEmpty(a.Bfield2)))
                {
                    e.AddFailure("Bfield2 not entered");
                }
            }
        });
c# blazor fluentvalidation
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.