Selective validation of child properties - Fluent Validation in MVC

后端 未结 3 1867
天命终不由人
天命终不由人 2021-02-10 14:00

I\'m using Fluent Validation with the Ninject.Web.Mvc.FluentValidation library to automatically wire up all of my validators (and use dependency injection to create the validato

3条回答
  •  孤城傲影
    2021-02-10 14:26

    If you don't want to auto wireup child validators you can add empty interface to child validator:

    public class PersonalDataValidator : AbstractValidator, IChildValidator

    And then in your factory:

    public class FluentValidatorFactory : ValidatorFactoryBase
    {
        private readonly IKernel _kernel;
    
        public FluentValidatorFactory(IKernel kernel)
        {
            _kernel = kernel;
        }
    
        public override IValidator CreateInstance(Type validatorType)
        {
            IValidator validator = _kernel.Resolve(validatorType) as IValidator;
    
            ////we dont want that windosr auto wires up all child validators. 
            var childValidator = validator as IChildValidator;
    
            if (childValidator == null)
            {
                return validator;
            }
    
                return null;
        }
    }
    

提交回复
热议问题