使用FluentValidation库自动进行属性验证过程 [英] Automate the validation process on properties using FluentValidation Library

查看:329
本文介绍了使用FluentValidation库自动进行属性验证过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很奇怪,有可能避免为每个需要验证的字段编写规则,例如,除Remarks外,所有属性都必须经过验证.而且我在考虑避免为每个属性编写RuleFor.

Wondering is there a possibility to avoid writing rules for every fields that needs to get validated, for an example all the properties must be validated except Remarks. And I was thinking to avoid writing RuleFor for every property.

public class CustomerDto
{
    public int CustomerId { get; set; }         //mandatory
    public string CustomerName { get; set; }    //mandatory
    public DateTime DateOfBirth { get; set; }   //mandatory
    public decimal Salary { get; set; }         //mandatory
    public string Remarks { get; set; }         //optional 
}

public class CustomerValidator : AbstractValidator<CustomerDto>
{
    public CustomerValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.CustomerName).NotEmpty();
        RuleFor(x => x.DateOfBirth).NotEmpty();
        RuleFor(x => x.Salary).NotEmpty();
    }
}

推荐答案

在这里:

public class Validator<T> : AbstractValidator<T>
{
    public Validator(Func<PropertyInfo, bool> filter) {
        foreach (var propertyInfo in typeof(T)
            .GetProperties()
            .Where(filter)) {
            var expression = CreateExpression(propertyInfo);
            RuleFor(expression).NotEmpty();
        }
    }

    private Expression<Func<T, object>> CreateExpression(PropertyInfo propertyInfo) {
        var parameter = Expression.Parameter(typeof(T), "x");
        var property = Expression.Property(parameter, propertyInfo);
        var conversion = Expression.Convert(property, typeof(object));
        var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter);

        return lambda;
    }
}

它可以这样使用:

    private static void ConfigAndTestFluent()
    {
        CustomerDto customer = new CustomerDto();
        Validator<CustomerDto> validator = new Validator<CustomerDto>(x=>x.Name!="Remarks"); //we specify here the matching filter for properties
        ValidationResult results = validator.Validate(customer);
    }

这篇关于使用FluentValidation库自动进行属性验证过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆