FluentValidation客户端验证不适用于继承的类

时间:2016-09-16 06:52:32

标签: c# fluentvalidation

客户端验证适用于' CompanyName'罚款,但对于继承的类,即运输和计费不工作。请提出解决方案。

[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.");
        }
    }   

1 个答案:

答案 0 :(得分:0)

对于包含对象,fluentvalidation不能像您实现的那样工作。

为此,请参考来自流畅验证的复杂属性验证,并尝试使用以下代码。

[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());
    }
}