Posts

....
Technical Blog for .NET Developers ©

Thursday, October 21, 2021

Basic Validator

When we need to add logic rules with simplicity, we have the possibility of implement basic validations based on IoC principles

In this post we check the implementation of a ready-made generic validator


  
    public interface IValidator<M>
    {
        IValidator<M> AddRule(Expression<Func<M, bool>> rule);

        bool CheckRules(M item);
    }  
  
  


The interface is based on add boolean expressions


  
    public class Validator<M> : IValidator<M>
    {
        private List<Expression<Func<M, bool>>> Rules { get; set; } = new();

        public IValidator<M> AddRule(Expression<Func<M, bool>> rule)
        {
            this.Rules.Add(rule);

            return this;
        }

        public bool CheckRules(M item)
        {
            return this.Rules.TrueForAll(rule => rule.Compile()(item));
        }
    }
  
  


The implementation collects the rules


        static void Main(string[] args)
        {
            Console.WriteLine("Test Validator");

            Demo demo = new()
            {
                Kata = 200,
                Title = "Test"
            };

            IValidator<Demo> demoValidator = new Validator<Demo>();

            demoValidator.AddRule(d => d.Kata > 100)
                         .AddRule(d => !string.IsNullOrEmpty(d.Title));

            _ = demoValidator.CheckRules(demo);
        } 
  
  


METHOD SOFTWARE ® 2021