コード例 #1
0
        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);
            }

            for (var i = 0; i < context.Results.Count; i++)
            {
                var validatorItem = context.Results[i];
                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);
                }
            }

            // 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
                });
            }
        }
コード例 #2
0
        public void Validate_CanUseRequestServices_WithinValidationAttribute()
        {
            // Arrange
            var service = new Mock <IExampleService>();

            service.Setup(x => x.DoSomething()).Verifiable();

            var provider = new ServiceCollection().AddSingleton(service.Object).BuildServiceProvider();

            var httpContext = new Mock <HttpContext>();

            httpContext.SetupGet(x => x.RequestServices).Returns(provider);

            var attribute = new Mock <TestableValidationAttribute> {
                CallBase = true
            };

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Callback((object o, ValidationContext context) =>
            {
                var receivedService = context.GetService <IExampleService>();
                Assert.Equal(service.Object, receivedService);
                receivedService.DoSomething();
            });

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);

            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext
            {
                HttpContext = httpContext.Object
            },
                modelMetadata: _metadataProvider.GetMetadataForType(typeof(object)),
                metadataProvider: _metadataProvider,
                container: null,
                model: new object());

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            service.Verify();
        }
コード例 #3
0
        public void Validate_RequiredAndNotNullAtTopLevel_Valid()
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForProperty(typeof(string), "Length");
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                new RequiredAttribute(),
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: 123);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            Assert.Empty(result);
        }
コード例 #4
0
        public void Validate_SetsMemberName_AsExpected(
            ModelMetadata metadata,
            object container,
            object model,
            string expectedMemberName)
        {
            // Arrange
            var attribute = new Mock <TestableValidationAttribute> {
                CallBase = true
            };

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Callback((object o, ValidationContext context) =>
            {
                Assert.Equal(expectedMemberName, context.MemberName);
            })
            .Returns(ValidationResult.Success)
            .Verifiable();
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: container,
                model: model);

            // Act
            var results = validator.Validate(validationContext);

            // Assert
            Assert.Empty(results);
            attribute.VerifyAll();
        }
コード例 #5
0
        public void Validate_RequiredButNullAtTopLevel_Invalid()
        {
            // Arrange
            var metadata  = _metadataProvider.GetMetadataForProperty(typeof(string), "Length");
            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                new RequiredAttribute(),
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: null);

            // Act
            var result = validator.Validate(validationContext);

            // Assert
            var validationResult = result.Single();

            Assert.Empty(validationResult.MemberName);
            Assert.Equal(new RequiredAttribute().FormatErrorMessage("Length"), validationResult.Message);
        }
コード例 #6
0
            public void CreateValidators(ModelValidatorProviderContext context)
            {
                for (var i = 0; i < context.Results.Count; i++)
                {
                    var validatorItem = context.Results[i];
                    if (validatorItem.Validator != null)
                    {
                        continue;
                    }

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

                    var validator = new DataAnnotationsModelValidator(
                        new ValidationAttributeAdapterProvider(),
                        attribute,
                        stringLocalizer: null);

                    validatorItem.Validator = validator;

                    if (attribute is RequiredAttribute)
                    {
                        validatorItem.IsReusable = true;
                    }
                }
            }