/// <summary>
        /// Creates the server validation validators
        /// </summary>
        /// <param name="context"></param>
        public void CreateValidators(ModelValidatorProviderContext context)
        {
            bool shouldAddRequiredValidator = !(context.Results.Any(x => x.GetType().Equals(typeof(RequiredAttributeAdapter))));

            foreach (var validator in GetValidators(context.ModelMetadata, shouldAddRequiredValidator))
            {
                var validatorItem = new ValidatorItem();
                validatorItem.Validator  = validator;
                validatorItem.IsReusable = false;
                context.Results.Add(validatorItem);
            }
        }
예제 #2
0
        public void CreateValidators(ModelValidatorProviderContext context)
        {
            if (context.ModelMetadata.MetadataKind == ModelMetadataKind.Type)
            {
                var item = new ValidatorItem
                {
                    Validator  = new Valitator(_factory),
                    IsReusable = true,
                };

                context.Results.Add(item);
            }
            var test = context;
            //throw new System.NotImplementedException();
        }
        public void CreateValidators(ModelValidatorProviderContext context)
        {
            var stringLocalizerAdapter =
                _stringLocalizerFactory != null && _dataAnnotationLocalizerProvider != null && context.ModelMetadata.ModelType.HasInterface(typeof(IValidatableObject)) ?
                new StringLocalizerAdapter(_dataAnnotationLocalizerProvider(context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType, _stringLocalizerFactory)) :
                null;

            var validatableObjectAdapterFound = false;

            var results = context.Results;

            for (int i = 0, n = results.Count; i < n; i++)
            {
                var result = results[i];

                // 1. default messages of built-in validation attributes aren't localized by default (https://github.com/aspnet/Localization/issues/286);
                // the least cumbersome solution to this problem is setting the ErrorMessage property, which will ensure that the message will run through the localizer

                if (result.ValidatorMetadata is ValidationAttribute validationAttribute)
                {
                    validationAttribute.AdjustToMvcLocalization();
                }

                // 2. support for ExtendedValidationResult localization in the case of IValidatableObject

                if (stringLocalizerAdapter != null)
                {
                    // we need to check type by name because unfortunately ValidatableObjectAdapter is internal
                    if (result.Validator != null && result.Validator.GetType().FullName == "Microsoft.AspNetCore.Mvc.DataAnnotations.ValidatableObjectAdapter")
                    {
                        results[i] = new ValidatorItem(result.ValidatorMetadata)
                        {
                            Validator  = new CustomValidatableObjectAdapter(_validationAttributeAdapterProvider, stringLocalizerAdapter),
                            IsReusable = result.IsReusable,
                        };

                        validatableObjectAdapterFound = true;
                    }
                }
            }

            if (stringLocalizerAdapter != null)
            {
                Debug.Assert(validatableObjectAdapterFound, "Microsoft.AspNetCore.Mvc.DataAnnotations internals have apparently changed.");
            }
        }
예제 #4
0
    public void GetModelValidators_ReturnsValidatorsFromAllProviders()
    {
        // Arrange
        var validatorMetadata = new object();
        var validator1        = new ValidatorItem(validatorMetadata);
        var validator2        = new ValidatorItem(validatorMetadata);
        var validator3        = new ValidatorItem(validatorMetadata);

        var provider1 = new Mock <IModelValidatorProvider>();

        provider1.Setup(p => p.CreateValidators(It.IsAny <ModelValidatorProviderContext>()))
        .Callback <ModelValidatorProviderContext>(c =>
        {
            c.Results.Add(validator1);
            c.Results.Add(validator2);
        });

        var provider2 = new Mock <IModelValidatorProvider>();

        provider2.Setup(p => p.CreateValidators(It.IsAny <ModelValidatorProviderContext>()))
        .Callback <ModelValidatorProviderContext>(c =>
        {
            c.Results.Add(validator3);
        });

        var compositeModelValidator = new CompositeModelValidatorProvider(new[] { provider1.Object, provider2.Object });
        var modelMetadata           = new EmptyModelMetadataProvider().GetMetadataForType(typeof(string));

        // Act
        var validatorProviderContext = new ModelValidatorProviderContext(modelMetadata, new List <ValidatorItem>());

        compositeModelValidator.CreateValidators(validatorProviderContext);

        // Assert
        Assert.Equal(
            new[] { validator1, validator2, validator3 },
            validatorProviderContext.Results.ToArray());
    }
        public void CreateValidators(ModelValidatorProviderContext context)
        {
            IStringLocalizer stringLocalizer = null;

            if (_stringLocalizerFactory != null && _options.Value.DataAnnotationLocalizerProvider != null)
            {
                stringLocalizer = _options.Value.DataAnnotationLocalizerProvider(
                    context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
                    _stringLocalizerFactory);
            }
            var metadata             = context.ModelMetadata;
            var isPropertyValidation = metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName);
            var rules = ValidationManager.GetValidationRules(metadata.ContainerType, metadata.PropertyName);

            if (rules == null)
            {
                return;
            }
            foreach (var rule in rules)
            {
                var validationAttribute = rule.CreateValidationAttribute();
                if (validationAttribute == null)
                {
                    continue;
                }
                var validatorItem = new ValidatorItem(validationAttribute);
                if (validatorItem.Validator != null)
                {
                    continue;
                }

                var attribute = validatorItem.ValidatorMetadata as ValidationAttribute;
                if (attribute == null)
                {
                    continue;
                }

                var validator = new DataAnnotationsModelValidator(
                    _validationAttributeAdapterProvider,
                    attribute,
                    stringLocalizer);

                validatorItem.Validator  = validator;
                validatorItem.IsReusable = true;
                // Inserts validators based on whether or not they are 'required'. We want to run
                // 'required' validators first so that we get the best possible error message.
                if (attribute is RequiredAttribute)
                {
                    context.Results.Remove(validatorItem);
                    context.Results.Insert(0, validatorItem);
                }
                context.Results.Add(validatorItem);
            }

            // Produce a validator if the type supports IValidatableObject
            if (typeof(IValidatableObject).IsAssignableFrom(context.ModelMetadata.ModelType))
            {
                context.Results.Add(new ValidatorItem
                {
                    Validator  = new ValidatableObjectAdapter(),
                    IsReusable = true
                });
            }
        }