FluentValidation rule for null object

后端 未结 9 1131
遥遥无期
遥遥无期 2020-12-25 10:44

I\'ve been trying to work out how to create a FluentValidation rule that checks if the instance of an object it\'s validating is not null, prior to validating it\'s properti

9条回答
  •  梦毁少年i
    2020-12-25 11:11

    As the above solutions didn't work for me (FluentValidation, Version=6.2.1.0 for Net45), I am posting what I did. This is just a simple replacement/wrapper for ValidateAndThrow extension method.

    public static class ValidatorExtensions
    {
        public static void ValidateAndThrowNotNull(this IValidator validator, T instance)
        {
            if (instance == null)
            {
                var validationResult = new ValidationResult(new[] { new ValidationFailure("", "Instance cannot be null") });
                throw new ValidationException(validationResult.Errors);
            }
            validator.ValidateAndThrow(instance);
        }
    }
    

提交回复
热议问题