Пример #1
0
        public void Validate_ReturnsMemberName_IfItIsDifferentFromDisplayName()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel));
            var model    = new SampleModel();

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

            attribute.Protected()
            .Setup <ValidationResult>("IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>())
            .Returns(new ValidationResult("Name error", new[] { "Name" }));

            var validator         = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer: null);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Model    = model,
            };

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

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal("Name", validationResult.MemberName);
        }
Пример #2
0
        public void Validate_ReturnsMemberName_IfItIsDifferentFromDisplayName()
        {
            // Arrange
            var metadata = _metadataProvider.GetMetadataForType(typeof(SampleModel));
            var model    = new SampleModel();

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

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Returns(new ValidationResult("Name error", new[] { "Name" }));

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

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

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal("Name", validationResult.MemberName);
        }
Пример #3
0
        public void Validate_ReturnsSingleValidationResult_IfOneMemberNameIsSpecified()
        {
            // Arrange
            const string errorMessage = "A different error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(object));
            var model    = new object();

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

            attribute.Protected()
            .Setup <ValidationResult>("IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>())
            .Returns(new ValidationResult(errorMessage, new[] { "FirstName" }));

            var validator         = new DataAnnotationsModelValidator(attribute.Object, stringLocalizer: null);
            var validationContext = new ModelValidationContext()
            {
                Metadata = metadata,
                Model    = model,
            };

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

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Equal("FirstName", validationResult.MemberName);
        }
        public void ValidateReturnsSingleValidationResultIfMemberNameSequenceIsEmpty()
        {
            // Arrange
            const string errorMessage = "Some error message";

            var modelExplorer = _metadataProvider
                                .GetModelExplorerForType(typeof(string), "Hello")
                                .GetExplorerForProperty("Length");

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

            attribute.Protected()
            .Setup <ValidationResult>("IsValid", ItExpr.IsAny <object>(), ItExpr.IsAny <ValidationContext>())
            .Returns(new ValidationResult(errorMessage, memberNames: null));
            var validator = new DataAnnotationsModelValidator(attribute.Object);

            var validationContext = CreateValidationContext(modelExplorer);

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

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Empty(validationResult.MemberName);
        }
Пример #5
0
        public IEnumerable <ModelValidationResult> Validate(ModelValidationContext validationContext)
        {
            var metadata   = validationContext.Metadata;
            var memberName = metadata.PropertyName ?? metadata.ModelType.Name;
            var container  = validationContext.Container;

            var context = new ValidationContext(container ?? validationContext.Model)
            {
                DisplayName = metadata.GetDisplayName(),
                MemberName  = memberName
            };

            var result = Attribute.GetValidationResult(validationContext.Model, context);

            if (result != ValidationResult.Success)
            {
                // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidator) to
                // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append
                // the returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the
                // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want
                // (person.Name.Name). However the invoking validator does not have a way to distinguish between these
                // two cases. Consequently we'll only set MemberName if this validation returns a MemberName that is
                // different from the property being validated.

                var errorMemberName = result.MemberNames.FirstOrDefault();
                if (string.Equals(errorMemberName, memberName, StringComparison.Ordinal))
                {
                    errorMemberName = null;
                }

                string errorMessage = null;
                if (_stringLocalizer != null &&
                    !string.IsNullOrEmpty(Attribute.ErrorMessage) &&
                    string.IsNullOrEmpty(Attribute.ErrorMessageResourceName) &&
                    Attribute.ErrorMessageResourceType == null)
                {
                    errorMessage = _stringLocalizer[Attribute.ErrorMessage];
                }

                var validationResult = new ModelValidationResult(errorMemberName, errorMessage ?? result.ErrorMessage);
                return(new ModelValidationResult[] { validationResult });
            }

            return(Enumerable.Empty <ModelValidationResult>());
        }
        public IEnumerable<ModelValidationResult> Validate(ModelValidationContext validationContext)
        {
            var metadata = validationContext.Metadata;
            var memberName = metadata.PropertyName ?? metadata.ModelType.Name;
            var container = validationContext.Container;

            var context = new ValidationContext(container ?? validationContext.Model)
            {
                DisplayName = metadata.GetDisplayName(),
                MemberName = memberName
            };

            var result = Attribute.GetValidationResult(validationContext.Model, context);
            if (result != ValidationResult.Success)
            {
                // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidator) to
                // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append
                // the returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the
                // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want
                // (person.Name.Name). However the invoking validator does not have a way to distinguish between these
                // two cases. Consequently we'll only set MemberName if this validation returns a MemberName that is
                // different from the property being validated.

                var errorMemberName = result.MemberNames.FirstOrDefault();
                if (string.Equals(errorMemberName, memberName, StringComparison.Ordinal))
                {
                    errorMemberName = null;
                }

                string errorMessage = null;
                if (_stringLocalizer != null &&
                    !string.IsNullOrEmpty(Attribute.ErrorMessage) &&
                    string.IsNullOrEmpty(Attribute.ErrorMessageResourceName) &&
                    Attribute.ErrorMessageResourceType == null)
                {
                    errorMessage = _stringLocalizer[Attribute.ErrorMessage];
                }

                var validationResult = new ModelValidationResult(errorMemberName, errorMessage ?? result.ErrorMessage);
                return new ModelValidationResult[] { validationResult };
            }

            return Enumerable.Empty<ModelValidationResult>();
        }
Пример #7
0
        public void Validate_ReturnsSingleValidationResult_IfOneMemberNameIsSpecified()
        {
            // Arrange
            const string errorMessage = "A different error message";

            var metadata = _metadataProvider.GetMetadataForType(typeof(object));
            var model    = new object();

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

            attribute
            .Setup(p => p.IsValidPublic(It.IsAny <object>(), It.IsAny <ValidationContext>()))
            .Returns(new ValidationResult(errorMessage, new[] { "FirstName" }));

            var validator = new DataAnnotationsModelValidator(
                new ValidationAttributeAdapterProvider(),
                attribute.Object,
                stringLocalizer: null);
            var validationContext = new ModelValidationContext(
                actionContext: new ActionContext(),
                modelMetadata: metadata,
                metadataProvider: _metadataProvider,
                container: null,
                model: model);

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

            // Assert
            ModelValidationResult validationResult = Assert.Single(results);

            Assert.Equal(errorMessage, validationResult.Message);
            Assert.Equal("FirstName", validationResult.MemberName);
        }