【问题标题】:FluentValidation client side validation not working for inherited classFluentValidation 客户端验证不适用于继承的类
【发布时间】:2016-09-16 06:52:32
【问题描述】:

客户端验证适用于“公司名称”,但对于继承的类,即运输和计费它不起作用。请提出解决方案。

[Validator(typeof(ClientValidator))]
public class Client
{
    public string CompanyName{get;set;}

    private volatile Contact Shipping = null;
    private volatile Contact Billing = null;

}

public class Contact : Address
{

}

public class Address
{

public String Name{get;set;}

    public String Phone{get;set;}
}


public class ClientValidator : AbstractValidator<Client>

{

        public ClientValidator()

{

RuleFor(x => x.CompanyName).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");


            RuleFor(x => x.Shipping.Name).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");

            RuleFor(x => x.Shipping.Phone).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
            RuleFor(x => x.Billing.Name).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
            RuleFor(x => x.Billing.Phone).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
        }
    }   

【问题讨论】:

    标签: c# fluentvalidation


    【解决方案1】:

    对于包含对象,fluentvalidation 无法正常工作。

    为此,请参考 fluent 验证中的复杂属性验证,并尝试使用以下代码。

    [Validator(typeof(ClientValidator))]
    public class Client
    {
        public string CompanyName{get;set;}
        private volatile Contact Shipping = null;
        private volatile Contact Billing = null;
    }
    
    public class Contact : Address
    {
    
    }
    
    public class Address
    {
        public String Name{get;set;}
        public String Phone{get;set;}
    }
    
    public class AddressValidator : AbstractValidator<Address>
    {
        public ClientValidator()
        {
            RuleFor(x => x.Name).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
            RuleFor(x => x.Phone).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
        }
    } 
    
    public class ClientValidator : AbstractValidator<Client>
    {
        public ClientValidator()
        {
            RuleFor(x => x.CompanyName).NotNull().WithMessage("Required").Length(1, 15).WithMessage("Length issue.");
            RuleFor(x => x.Shipping).SetValidator(new AddressValidator());
            RuleFor(x => x.Billing).SetValidator(new AddressValidator());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2014-03-27
      • 2023-02-21
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多