jeudi 14 mars 2019

FluentValidation: Apply Rule for all property by default automatically

I have a class Person with some property, so I want to apply FluentValidation Rule for all property by default automatically

  • Example:
    • string: NotNull(), NotEmpty(), Length()...
    • enum: IsInEnum()
    • List: NotNull() ot something else...
    • ...

Person and Extension method

public enum Gender { Male, Female }

public class Person
{
    public Gender Gender { get; set; }
    public string Name { get; set; }
    public List<string> Notes { get; set; }
}

public static class Extension
{
    public static Expression<Func<T, TProperty>> GenerateExpression<T, TProperty>(PropertyInfo propInfo)
    {
        ParameterExpression paramExp = Expression.Parameter(typeof(T));
        MemberExpression memExp = Expression.Property(paramExp, propInfo);
        UnaryExpression unaryExp = Expression.Convert(memExp, propInfo.PropertyType);
        return Expression.Lambda<Func<T, TProperty>>(unaryExp, paramExp);
    }
}

Base Validator

I use Extension.GenerateExpression to build Expression base on list Properties then pass it into RuleFor(), but it only work with string type
I don't know how to handle other data types

public class BaseValidator<T> : AbstractValidator<T>
{
    public BaseValidator()
    {
        ParameterExpression paramExp = Expression.Parameter(typeof(T));

        foreach (PropertyInfo propInfo in typeof(T).GetProperties())
        {
            // String [WORKED]
            if (propInfo.PropertyType == typeof(string))
            {
                Expression<Func<T, string>> expression = Extension.GenerateExpression<T, string>(propInfo);
                RuleFor(expression).Length(1, 10); //.Matches("pattern");
            }

            // List [NOT WORK]
            else if (propInfo.PropertyType.IsGenericType)
            {
                Expression<Func<T, object>> expression = Extension.GenerateExpression<T, object>(propInfo);
                RuleFor(expression).NotNull(); //ItemsInRange(1, 2);
            }

            // Enum [EXCEPTION]
            else if (propInfo.PropertyType.IsEnum)
            {
                Expression<Func<T, Enum>> expression = Extension.GenerateExpression<T, Enum>(propInfo);
                // Expression of type 'Gender' cannot be used for return type 'System.Enum''
                RuleFor(expression).IsInEnum();
            }

            // Other type [How to handle?]
            else
            {
                //Expression<Func<T, ???>> expression = GenerateExpression<T, ???>(propInfo);
            }
        }
    }
}

Person Validator

public class PersonValidator : BaseValidator<Person> { }

Program

public class Program
{
    public static void Main(string[] args)
    {
        Person person = new Person
        {
            Name = "Name",
            Gender = Gender.Male,
            Notes = new List<string> { "Note 1", "Note 2" }
        };

        PersonValidator validation = new PersonValidator();
        ValidationResult result = validation.Validate(person);

        foreach (var error in result.Errors)
        {
            Console.WriteLine(error);
        }

        Console.ReadKey();
    }
}

Help me, please!
Thanks!





Aucun commentaire:

Enregistrer un commentaire