Ejemplo n.º 1
0
        public IEnumerable <ValidationResult> Validate(FluentValidation.ValidationContext validationContext)
        {
            var validator = new SkillDtoValidator();
            var result    = validator.Validate(this);

            return(result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName })));
        }
        //1. [Required]
        //2. Other attributes
        //3. IValidatableObject Implementation
        public IEnumerable <ValidationResult> Validate(object o)
        {
            var attributeValidationContext = new System.ComponentModel.DataAnnotations.ValidationContext(o, _serviceProvider, new Dictionary <object, object>());

            var validationResults = new List <ValidationResult>();
            var isValid           = Validator.TryValidateObject(
                attributeValidationContext.ObjectInstance,
                attributeValidationContext,
                validationResults,
                validateAllProperties: true); // if true [Required] + Other attributes

            var attributeValidationResults = validationResults.Where(r => r != ValidationResult.Success);

            var fluentValidationContext = new FluentValidation.ValidationContext(o);

            var fluentValidationFailures = _validators
                                           .Select(v => v.Validate(fluentValidationContext))
                                           .SelectMany(result => result.Errors)
                                           .Where(f => f != null)
                                           .ToList();

            var fluentValidationResults = fluentValidationFailures.Select(f => new ValidationResult(f.ErrorMessage, new string[] { f.PropertyName }));

            return(attributeValidationResults.Concat(fluentValidationResults));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取对象的某一项属性错误
        /// </summary>
        /// <param name="obj">待校验的对象</param>
        /// <param name="propertyName">待校验的属性名</param>
        /// <param name="validator">FluentValidation验证器</param>
        /// <returns>错误信息</returns>
        public static ValidationResult GetPropertyErrorMsg(object obj, string propertyName, IValidator validator = null)
        {
            if (string.IsNullOrWhiteSpace(propertyName) || obj == null)
            {
                return(new ValidationResult(string.Empty));
            }

            if (validator != null)
            {
                var context = new ValidationContext(obj, null, new MemberNameValidatorSelector(new[] { propertyName }));
                var result  = validator.Validate(context);

                var error = result.Errors.FirstOrDefault(x => x.PropertyName.Equals(propertyName))?.ErrorMessage;
                if (!string.IsNullOrEmpty(error))
                {
                    return(new ValidationResult(error));
                }
            }

            var vc = new System.ComponentModel.DataAnnotations.ValidationContext(obj, null, null)
            {
                MemberName = propertyName
            };
            var res = new List <ValidationResult>();

            Validator.TryValidateProperty(obj.GetType().GetProperty(propertyName)?.GetValue(obj, null), vc, res);
            if (res.Any())
            {
                return(new ValidationResult(string.Join(Environment.NewLine,
                                                        res.Select(r => r.ErrorMessage).ToArray())));
            }

            return(new ValidationResult(string.Empty));
        }
Ejemplo n.º 4
0
        private ValidationResult GetValidationResult(IBaseRequest request)
        {
            if (request == null)
            {
                return(new ValidationResult(new[] { new ValidationFailure("Request", "Request cannot be null") }));
            }
            var context = new ValidationContext(request);

            return(this.validators
                   .Where(x => x.CanValidateInstancesOfType(request.GetType()))
                   .Select(v => v.Validate(context))
                   .FirstOrDefault());
        }
Ejemplo n.º 5
0
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context  = new ValidationContext(request);
            var failures = _validators.Select(x => x.Validate(context))
                           .SelectMany(x => x.Errors)
                           .Where(x => x != null);

            if (failures.Any())
            {
                throw new ValidationException(failures);
            }

            return(next());
        }
        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            if (_validators.Any())
            {
                var context = new FluentValidation.ValidationContext(request);

                var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
                var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();

                if (failures.Count != 0)
                    throw new Exceptions.ValidationException(failures);
            }
            return await next();
        }
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context = new ValidationContext(request);

            var failures = _validators
                           .Select(v => v.Validate(context))
                           .SelectMany(result => result.Errors)
                           .Where(f => f != null)
                           .ToList();

            if (failures.Count != 0)
            {
                throw new ValidationException(failures);
            }
            return(next());
        }
Ejemplo n.º 8
0
        public async Task <Unit> Handle(AddCategoryCommand request, CancellationToken cancellationToken)
        {
            var context  = new FluentValidation.ValidationContext(request);
            var failures = validators
                           .Select(x => x.Validate(context))
                           .SelectMany(x => x.Errors)
                           .Where(x => x != null)
                           .ToList();

            if (failures.Count > 0)
            {
                throw new FluentValidation.ValidationException(failures);
            }

            categoryRepository.Add(new Domain.Products.Category(request.Name));
            return(await Task.FromResult <Unit>(Unit.Value));
        }
        public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var context       = new ValidationContext(request);
            var errorResponse = new Error.ErrorResponse();

            foreach (var validation in _validators)
            {
                var validationResponse = await validation.ValidateAsync(context);

                foreach (var error in validationResponse.Errors)
                {
                    errorResponse.AddError(error.ErrorMessage);
                }
            }

            errorResponse.ThrowIfErrors();

            return(await next());
        }
Ejemplo n.º 10
0
        private ICollection <ValidationResult> PerformValidation(ValidationContext validationContext)
        {
            // Don't do any processing if there are no FluentValidation validators
            if (_validators == null || _validators.Length == 0)
            {
                return(EmptyValidationResults);
            }

            var objectType = validationContext.InstanceToValidate.GetType();

            // Run all registered fluent validators that can validate the specified type using the supplied rule set name
            var fluentValidationResults = GetValidators(objectType)
                                          .Select(x => x.Validate(validationContext));

            // Combine and adapt the results to DataAnnotation's ValidationResult
            var validationResults = fluentValidationResults
                                    .SelectMany(x => x.Errors.Select(e => new ValidationResult(e.ErrorMessage)));

            return(validationResults.ToList());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取对象的某一项属性错误
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">待校验的对象</param>
        /// <param name="propertyName">待校验的属性名</param>
        /// <param name="validator">FluentValidation验证器</param>
        /// <returns></returns>
        public static ValidationResult GetPropertyErrorMsg <T>(T obj, string propertyName, IValidator <T> validator)
        {
            if (validator == null)
            {
                throw new ArgumentNullException(nameof(validator));
            }

            if (string.IsNullOrWhiteSpace(propertyName) || obj == null)
            {
                return(new ValidationResult(string.Empty));
            }

            var context = new ValidationContext(obj, null, new MemberNameValidatorSelector(new[] { propertyName }));
            var result  = validator.Validate(context);

            var error = result.Errors.FirstOrDefault(x => x.PropertyName.Equals(propertyName))?.ErrorMessage;

            if (!string.IsNullOrEmpty(error))
            {
                return(new ValidationResult(error));
            }

            return(new ValidationResult(string.Empty));
        }
Ejemplo n.º 12
0
 public ValidationResult AfterMvcValidation(ControllerContext cc, ValidationContext context, ValidationResult result)
 {
     return(new ValidationResult());
 }
Ejemplo n.º 13
0
 public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context)
 {
     return(null);
 }
Ejemplo n.º 14
0
        public ValidationContext BeforeMvcValidation(ControllerContext cc, ValidationContext context)
        {
            var newContext = context.Clone(selector: new FluentValidation.Internal.MemberNameValidatorSelector(properties));

            return(newContext);
        }
Ejemplo n.º 15
0
 public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext)
 {
     return(validationContext);
 }
Ejemplo n.º 16
0
 public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result)
 {
     return(new ValidationResult()); //empty errors
 }
Ejemplo n.º 17
0
        public void Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            IValidator validator = null;
            var        metadata  = model == null ? null : _modelMetadataProvider.GetMetadataForType(model.GetType());

            bool prependPrefix = true;

            if (model != null)
            {
                if (metadata.IsCollectionType)
                {
                    validator     = BuildCollectionValidator(prefix, metadata);
                    prependPrefix = false;
                }
                else
                {
                    validator = _validatorFactory.GetValidator(metadata.ModelType);
                }
            }

            if (validator == null)
            {
                // Use default impl if FV doesn't have a validator for the type.
                var visitor = new ValidationVisitor(
                    actionContext,
                    _validatorProvider,
                    _validatorCache,
                    _modelMetadataProvider,
                    validationState);

                visitor.Validate(metadata, prefix, model);

                return;
            }

            foreach (var value in actionContext.ModelState.Values
                     .Where(v => v.ValidationState == ModelValidationState.Unvalidated))
            {
                // Set all unvalidated states to valid. If we end up adding an error below then that properties state
                // will become ModelValidationState.Invalid and will set ModelState.IsValid to false

                value.ValidationState = ModelValidationState.Valid;
            }


            var customizations = GetCustomizations(actionContext, model.GetType(), prefix);

            var selector    = customizations.ToValidatorSelector();
            var interceptor = customizations.GetInterceptor() ?? (validator as IValidatorInterceptor);
            var context     = new FluentValidation.ValidationContext(model, new FluentValidation.Internal.PropertyChain(), selector);

            if (interceptor != null)
            {
                // Allow the user to provide a customized context
                // However, if they return null then just use the original context.
                context = interceptor.BeforeMvcValidation((ControllerContext)actionContext, context) ?? context;
            }

            var result = validator.Validate(context);

            if (interceptor != null)
            {
                // allow the user to provice a custom collection of failures, which could be empty.
                // However, if they return null then use the original collection of failures.
                result = interceptor.AfterMvcValidation((ControllerContext)actionContext, context, result) ?? result;
            }

            if (!string.IsNullOrEmpty(prefix))
            {
                prefix = prefix + ".";
            }

            foreach (var modelError in result.Errors)
            {
                string key = modelError.PropertyName;

                if (prependPrefix)
                {
                    key = prefix + key;
                }
                else
                {
                    key = key.Replace(ModelKeyPrefix, string.Empty);
                }

                // See if there's already an item in the ModelState for this key.
                if (actionContext.ModelState.ContainsKey(key))
                {
                    actionContext.ModelState[key].Errors.Clear();
                }

                actionContext.ModelState.AddModelError(key, modelError.ErrorMessage);
            }


            // Otherwise:

            /*
             *
             */
        }