Esempio n. 1
0
        public void ClientRulesWithMinLengthAttributeAndCustomMessage()
        {
            // Arrange
            var propertyName = "Length";
            var message      = "Array must have at least {1} items.";
            var provider     = new DataAnnotationsModelMetadataProvider();
            var metadata     = provider.GetMetadataForProperty(() => null, typeof(string), propertyName);
            var attribute    = new MinLengthAttribute(2)
            {
                ErrorMessage = message
            };
            var adapter = new MinLengthAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(2, rule.ValidationParameters["min"]);
            Assert.Equal("Array must have at least 2 items.", rule.ErrorMessage);
        }
Esempio n. 2
0
    public void MinLengthAttribute_AddValidation_Localize()
    {
        // Arrange
        var provider = TestModelMetadataProvider.CreateDefaultProvider();
        var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

        var attribute = new MinLengthAttribute(6);

        attribute.ErrorMessage = "Property must be at least '{1}' characters long.";

        var expectedProperties = new object[] { "Length", 6 };
        var expectedMessage    = "Property must be at least '6' characters long.";

        var stringLocalizer = new Mock <IStringLocalizer>();

        stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
        .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

        var adapter = new MinLengthAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

        var actionContext = new ActionContext();
        var context       = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>());

        // Act
        adapter.AddValidation(context);

        // Assert
        Assert.Collection(
            context.Attributes,
            kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
            kvp => { Assert.Equal("data-val-minlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
            kvp => { Assert.Equal("data-val-minlength-min", kvp.Key); Assert.Equal("6", kvp.Value); });
    }
Esempio n. 3
0
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // Arrange
            var propertyName = "Length";
            var provider     = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata     = provider.GetMetadataForProperty(typeof(string), propertyName);

            var attribute = new MinLengthAttribute(2)
            {
                ErrorMessage = "Array must have at least {1} items."
            };
            var adapter = new MinLengthAttributeAdapter(attribute, stringLocalizer: null);

            var actionContext = new ActionContext();
            var context       = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-minlength", "original");
            context.Attributes.Add("data-val-minlength-min", "original");

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-minlength", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-minlength-min", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
Esempio n. 4
0
 private string BuildValidationWithMinLengthAttribute(MinLengthAttribute minAttribute, string propertyName)
 {
     return
         (string.Format(
              @"model['{0}'].extend({{ minLength: {{ params: {1},
                                                    message: '{2}' }} }});", propertyName, minAttribute.Length, minAttribute.LocalizableError()));
 }
        public void CreateWithStringRequestConstrainedbyMinLengthReturnsCorrectResult(int min)
        {
            // Arrange
            var minLengthAttribute = new MinLengthAttribute(min);

            var request = new FakeMemberInfo(
                new ProvidedAttribute(minLengthAttribute, true));

            var expectedRequest = new ConstrainedStringRequest(min, int.MaxValue);
            var expectedResult  = new object();
            var context         = new DelegatingSpecimenContext
            {
                OnResolve = r => expectedRequest.Equals(r) ? expectedResult : new NoSpecimen()
            };

            var sut = new MinAndMaxLengthAttributeRelay
            {
                RequestMemberTypeResolver = new DelegatingRequestMemberTypeResolver
                {
                    OnTryGetMemberType = r => typeof(string)
                }
            };

            // Act
            var result = sut.Create(request, context);

            // Assert
            Assert.Equal(expectedResult, result);
        }
Esempio n. 6
0
        public static MinLengthAttribute CreateMinLengthAttribute(int length, string errorMessage = null)
        {
            var returnValue = new MinLengthAttribute(length);

            UpdateErrorMessage(returnValue, errorMessage);
            return(returnValue);
        }
Esempio n. 7
0
        public void ClientRulesWithMinLengthAttribute_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new MinLengthAttribute(6);

            attribute.ErrorMessage = "Property must be at least '{1}' characters long.";

            var expectedProperties = new object[] { "Length", 6 };
            var expectedMessage    = "Property must be at least '6' characters long.";

            var stringLocalizer = new Mock <IStringLocalizer>();

            stringLocalizer.Setup(s => s[attribute.ErrorMessage, expectedProperties])
            .Returns(new LocalizedString(attribute.ErrorMessage, expectedMessage));

            var adapter = new MinLengthAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object);

            var actionContext = new ActionContext();
            var context       = new ClientModelValidationContext(actionContext, metadata, provider);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(6, rule.ValidationParameters["min"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
Esempio n. 8
0
        public void ClientRulesWithMinLengthAttributeAndCustomMessage()
        {
            // Arrange
            var propertyName = "Length";
            var message      = "Array must have at least {1} items.";
            var provider     = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata     = provider.GetMetadataForProperty(typeof(string), propertyName);
            var attribute    = new MinLengthAttribute(2)
            {
                ErrorMessage = message
            };
            var adapter           = new MinLengthAttributeAdapter(attribute, stringLocalizer: null);
            var serviceCollection = new ServiceCollection();
            var requestServices   = serviceCollection.BuildServiceProvider();
            var context           = new ClientModelValidationContext(metadata, provider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(2, rule.ValidationParameters["min"]);
            Assert.Equal("Array must have at least 2 items.", rule.ErrorMessage);
        }
Esempio n. 9
0
        public void ClientRulesWithMinLengthAttributeAndCustomMessage()
        {
            // Arrange
            string propertyName = "Length";
            string message      = "Array must have at least {1} items.";
            var    metadata     = ModelMetadataProviders.Current.GetMetadataForProperty(
                () => null,
                typeof(int[]),
                propertyName
                );
            var context   = new ControllerContext();
            var attribute = new MinLengthAttribute(2)
            {
                ErrorMessage = message
            };
            var adapter = new MinLengthAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules();

            // Assert
            ModelClientValidationRule rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(2, rule.ValidationParameters["min"]);
            Assert.Equal("Array must have at least 2 items.", rule.ErrorMessage);
        }
Esempio n. 10
0
        public void ClientRulesWithMinLengthAttribute()
        {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(
                () => null,
                typeof(string),
                "Length"
                );
            var context   = new ControllerContext();
            var attribute = new MinLengthAttribute(6);
            var adapter   = new MinLengthAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules();

            // Assert
            ModelClientValidationRule rule = Assert.Single(rules);

            Assert.Equal("minlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(6, rule.ValidationParameters["min"]);
            Assert.Equal(
                "The field Length must be a string or array type with a minimum length of '6'.",
                rule.ErrorMessage
                );
        }
Esempio n. 11
0
    public void MinLengthAttribute_AddValidation_AttributeAndCustomMessage()
    {
        // Arrange
        var propertyName = "Length";
        var provider     = TestModelMetadataProvider.CreateDefaultProvider();
        var metadata     = provider.GetMetadataForProperty(typeof(string), propertyName);

        var attribute = new MinLengthAttribute(2)
        {
            ErrorMessage = "Array must have at least {1} items."
        };
        var adapter = new MinLengthAttributeAdapter(attribute, stringLocalizer: null);

        var expectedMessage = "Array must have at least 2 items.";

        var actionContext = new ActionContext();
        var context       = new ClientModelValidationContext(actionContext, metadata, provider, new Dictionary <string, string>());

        // Act
        adapter.AddValidation(context);

        // Assert
        Assert.Collection(
            context.Attributes,
            kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
            kvp => { Assert.Equal("data-val-minlength", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
            kvp => { Assert.Equal("data-val-minlength-min", kvp.Key); Assert.Equal("2", kvp.Value); });
    }
Esempio n. 12
0
        /// <summary>
        /// 验证输入的最小长度
        /// </summary>
        /// <param name="box">验证框</param>
        /// <param name="length">最小长度</param>
        /// <param name="errorMessage">提示信息</param>
        /// <returns></returns>
        public static ValidBox MinLength(this ValidBox box, int length, string errorMessage)
        {
            var newBox = new MinLengthAttribute(length)
            {
                ErrorMessage = errorMessage
            }.ToValidBox();

            return(ValidBox.Merge(box, newBox));
        }
Esempio n. 13
0
        private static Errors ValidateProperty(PropertyInfo property, object entity, object value)
        {
            var errors = new Errors();

            RequiredAttribute.Validate(property, value, errors);
            MaxLengthAttribute.Validate(property, value, errors);
            MinLengthAttribute.Validate(property, value, errors);

            return(errors);
        }
Esempio n. 14
0
        /// <summary>
        /// Verify whether value is greater than or equal special maxlength.
        /// minLength must be greater than or equal to zero.
        /// Allow value is null
        /// </summary>
        /// <param name="value">Value</param>
        /// <param name="minLength">min length,must be greater than or equal to zero</param>
        /// <returns>Return whether the verification has passed</returns>
        public static bool MinLength(this object value, int minLength)
        {
            if (minLength < 0)
            {
                throw new ArgumentException($"{nameof(minLength)} must be greater than or equal to zero");
            }
            var minLengthAttribute = new MinLengthAttribute(minLength);

            return(minLengthAttribute.IsValid(value));
        }
Esempio n. 15
0
 private static void ApplyMinLengthAttribute(OpenApiSchema schema, MinLengthAttribute minLengthAttribute)
 {
     if (schema.Type == "array")
     {
         schema.MinItems = minLengthAttribute.Length;
     }
     else
     {
         schema.MinLength = minLengthAttribute.Length;
     }
 }
        public void MinLengthAdapter_SetsErrorMessage()
        {
            MinLengthAttribute attribute = new MinLengthAttribute(128);

            new MinLengthAdapter(attribute);

            String expected = Validations.MinLength;
            String actual   = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
Esempio n. 17
0
        /// <summary>
        /// Adds a MinLengthAttribute.
        /// </summary>
        /// <param name="length">The minimum allowable length of array or string data.</param>
        /// <param name="errMsg">Gets or sets an error message to associate with a validation control if validation fails.</param>
        /// <returns></returns>
        public BaValidatorList MinLength(int length, string errMsg = null)
        {
            var att = new MinLengthAttribute(length);

            if (errMsg != null)
            {
                att.ErrorMessage = errMsg;
            }
            Add(att);
            return(this);
        }
Esempio n. 18
0
        public void NullTest()
        {
            // arrange
            object value = null;

            // act
            var          attr   = new MinLengthAttribute(2);
            SingleReport result = attr.Validate(value);

            // assert
            Assert.AreEqual(true, result.IsValid);
        }
Esempio n. 19
0
        public void EqualMinTest()
        {
            // arrange
            string value = "15";

            // act
            var          attr   = new MinLengthAttribute(2);
            SingleReport result = attr.Validate(value);

            // assert
            Assert.AreEqual(true, result.IsValid);
        }
Esempio n. 20
0
        public void MinLengthAdapter_SetsErrorMessage()
        {
            MinLengthAttribute attribute = new MinLengthAttribute(128);
            ModelMetadata      metadata  = new DataAnnotationsModelMetadataProvider()
                                           .GetMetadataForProperty(null, typeof(AdaptersModel), "MinLength");

            new MinLengthAdapter(metadata, new ControllerContext(), attribute);

            String expected = Validations.MinLength;
            String actual   = attribute.ErrorMessage;

            Assert.Equal(expected, actual);
        }
Esempio n. 21
0
            private static Range GetRange(MinLengthAttribute minLengthAttribute, MaxLengthAttribute maxLengthAttribute)
            {
                var min = minLengthAttribute?.Length ?? 0;
                var max = maxLengthAttribute?.Length ?? int.MaxValue;

                // To avoid creation of empty strings/arrays.
                if (max > 0 && min == 0)
                {
                    min = 1;
                }

                return(new Range(min, max));
            }
Esempio n. 22
0
        public void Given_MinLengthAttribute_When_Visit_Invoked_Then_It_Should_Return_Result(int length)
        {
            var name      = "hello";
            var acceptor  = new OpenApiSchemaAcceptor();
            var type      = new KeyValuePair <string, Type>(name, typeof(decimal));
            var attribute = new MinLengthAttribute(length);

            this._visitor.Visit(acceptor, type, this._strategy, attribute);

            acceptor.Schemas.Should().ContainKey(name);
            acceptor.Schemas[name].Type.Should().Be("number");
            acceptor.Schemas[name].MinLength.Should().Be(length);
        }
Esempio n. 23
0
        protected override ValidationResult?IsValid(object?value, ValidationContext validationContext)
        {
            var required = new RequiredAttribute();
            var length   = new MinLengthAttribute(IdentityPasswordConstants.RequiredLength);

            if (!required.IsValid(value))
            {
                return(new ValidationResult(SharedValidationConstants.RequiredPassword));
            }

            return(!length.IsValid(value)
                ? new ValidationResult(SharedValidationConstants.InvalidPasswordLength)
                : ValidationResult.Success);
        }
Esempio n. 24
0
        public void Context_ShouldHave_MinValueConstraintWithCorrectValue()
        {
            Article article  = new Article();
            string  property = "Context";

            MinLengthAttribute attribute = article.GetType()
                                           .GetProperty(property)
                                           .GetCustomAttributes(false)
                                           .Where(p => p.GetType() == typeof(MinLengthAttribute))
                                           .Select(x => (MinLengthAttribute)x)
                                           .Single();

            Assert.AreEqual(ValidationConstants.ArticleContextMinLength, attribute.Length);
        }
        public void CheckMinLength()
        {
            var attr = new MinLengthAttribute(2);

            Assert.IsTrue(attr.IsValid(null), "#A1");
            Assert.IsFalse(attr.IsValid("1"), "#A2");

            Assert.IsTrue(attr.IsValid("12"), "#A3");
            Assert.IsTrue(attr.IsValid("123"), "#A4");

            Assert.IsFalse(attr.IsValid(BuildQuickList(1)), "#A5");
            Assert.IsTrue(attr.IsValid(BuildQuickList(2)), "#A6");
            Assert.IsTrue(attr.IsValid(BuildQuickList(3)), "#A7");
        }
        public void CreateWithFiniteSequenceRequestConstrainedbyMinAndMaxLengthReturnsCorrectResult(int min, int max)
        {
            // Arrange
            var memberType = typeof(string[]);
            var randomNumberWithinRange = (min + max) / 2;

            var minLengthAttribute = new MinLengthAttribute(min);
            var maxLengthAttribute = new MaxLengthAttribute(max);

            var request = new FakeMemberInfo(
                new ProvidedAttribute(minLengthAttribute, true),
                new ProvidedAttribute(maxLengthAttribute, true));

            var expectedRangedNumberRequest   = new RangedNumberRequest(typeof(int), min, max);
            var expectedFiniteSequenceRequest = new FiniteSequenceRequest(
                memberType.GetElementType(),
                randomNumberWithinRange);

            var expectedResult = new List <string>();

            var context = new DelegatingSpecimenContext
            {
                OnResolve = r =>
                {
                    if (r.Equals(expectedRangedNumberRequest))
                    {
                        return(randomNumberWithinRange);
                    }
                    if (r.Equals(expectedFiniteSequenceRequest))
                    {
                        return(expectedResult);
                    }
                    return(new NoSpecimen());
                }
            };

            var sut = new MinAndMaxLengthAttributeRelay
            {
                RequestMemberTypeResolver = new DelegatingRequestMemberTypeResolver
                {
                    OnTryGetMemberType = r => memberType
                }
            };

            // Act
            var result = sut.Create(request, context);

            // Assert
            Assert.Equal(expectedResult, result);
        }
Esempio n. 27
0
        public void Name_ShouldHave_MinValueConstraintWithCorrectValue()
        {
            League league   = new League();
            string property = "Name";

            MinLengthAttribute attribute = league.GetType()
                                           .GetProperty(property)
                                           .GetCustomAttributes(false)
                                           .Where(p => p.GetType() == typeof(MinLengthAttribute))
                                           .Select(x => (MinLengthAttribute)x)
                                           .Single();

            Assert.AreEqual(ValidationConstants.LeagueNameMinLength, attribute.Length);
        }
Esempio n. 28
0
        public static MvcHtmlString FloatingTextAreaFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, bool readOnly = false, int rows = 3, bool hasLablel = true)
        {
            TagBuilder    tag  = new TagBuilder("textarea");
            ModelMetadata meta = ModelMetadata.FromLambdaExpression(expression, html.ViewData);


            tag.Attributes.Add("placeholder", meta.DisplayName);
            tag.Attributes.Add("class", "form-control");
            if ((readOnly || meta.IsReadOnly) && !tag.Attributes.ContainsKey("readonly"))
            {
                tag.Attributes.Add("readonly", "readonly");
            }
            MemberExpression body = expression.Body as MemberExpression;

            if (body != null)
            {
                MaxLengthAttribute maxLengthAttribute = (body.Member.GetCustomAttributes(typeof(MaxLengthAttribute), false)).FirstOrDefault() as MaxLengthAttribute;
                if (maxLengthAttribute != null)
                {
                    tag.Attributes.Add("data-rule-maxlength", maxLengthAttribute.Length.ToString());
                }

                MinLengthAttribute minLengthAttribute = (body.Member.GetCustomAttributes(typeof(MinLengthAttribute), false)).FirstOrDefault() as MinLengthAttribute;
                if (minLengthAttribute != null)
                {
                    tag.Attributes.Add("data-rule-minlength", minLengthAttribute.Length.ToString());
                }

                RequiredAttribute requiredAttribute = (body.Member.GetCustomAttributes(typeof(RequiredAttribute), false)).FirstOrDefault() as RequiredAttribute;
                if (requiredAttribute != null)
                {
                    tag.Attributes.Add("required", "true");
                }
            }
            tag.Attributes.Add("rows", rows.ToString());
            tag.Attributes.Add("name", meta.PropertyName.ToLower());
            tag.Attributes.Add("id", meta.PropertyName.ToLower());

            var value = GetModelValue(meta);

            if (!string.IsNullOrEmpty(value))
            {
                tag.SetInnerText(value);
            }

            var label = hasLablel ? FloatingLabelFor(html, expression, tag.Attributes.Keys.Contains("required")) : null;

            return(new MvcHtmlString(label + tag.ToString()));
        }
Esempio n. 29
0
        public void Have_MinValueConstraintWithCorrectValue()
        {
            // Arrange
            Article article = new Article();

            // Act
            MinLengthAttribute attribute = article.GetType()
                                           .GetProperty(PropertyName)
                                           .GetCustomAttributes(false)
                                           .Where(p => p.GetType() == typeof(MinLengthAttribute))
                                           .Select(x => (MinLengthAttribute)x)
                                           .Single();

            // Assert
            Assert.AreEqual(ValidationConstraints.ArticleContentMinLength, attribute.Length);
        }
Esempio n. 30
0
        public static MinLengthAttribute CreateMinLengthAttribute(this XElement annotation)
        {
            const string NAME = "MinLength";
            string       name = annotation.Attribute(SchemaVocab.Name).Value;

            if (name != NAME)
            {
                throw new ArgumentException(string.Format(SchemaMessages.ExpectedBut, NAME, name));
            }

            string             value     = annotation.GetArgumentValue("Length");
            int                length    = int.Parse(value);
            MinLengthAttribute attribute = new MinLengthAttribute(length);

            FillValidationAttribute(attribute, annotation);
            return(attribute);
        }
 public static void GetValidationResult_InvalidValue_ReturnsNotNull(int length, object value)
 {
     ValidationResult result = new MinLengthAttribute(length).GetValidationResult(value, s_testValidationContext);
     Assert.NotNull(result.ErrorMessage);
 }
 public static void GetValidationResult_InvalidLength_ThrowsInvalidOperationException()
 {
     var attribute = new MinLengthAttribute(-1);
     Assert.Throws<InvalidOperationException>(() => attribute.GetValidationResult("Rincewind", s_testValidationContext));
 }