public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters_Localize()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(8);
            attribute.ErrorMessage = "Property must not be longer than '{1}' characters.";

            var expectedMessage = "Property must not be longer than '8' characters.";

            var stringLocalizer = new Mock<IStringLocalizer>();
            var expectedProperties = new object[] { "Length", 0, 8 };

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

            var adapter = new StringLengthAttributeAdapter(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("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal(expectedMessage, rule.ErrorMessage);
        }
        public void ClientRulesWithStringLengthAttribute()
        {
            // Arrange
            var metadata  = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length");
            var context   = new ControllerContext();
            var attribute = new StringLengthAttribute(10)
            {
                MinimumLength = 3
            };
            var adapter = new StringLengthAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules()
                        .OrderBy(r => r.ValidationType)
                        .ToArray();

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

            Assert.Equal("length", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(3, rule.ValidationParameters["min"]);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("The field Length must be a string with a minimum length of 3 and a maximum length of 10.", rule.ErrorMessage);
        }
        /// <summary>
        /// Input text de un campo de una entidad
        /// EL title del input se obtiene del Display Description del Metadata (Si esta definido)
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="tabIndex"></param>
        /// <param name="readOnly"></param>
        /// <param name="sClass"></param>
        /// <param name="HtmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString HelpInputTextFor <TModel, TValue>(this HtmlHelper <TModel> htmlHelper,
                                                                      Expression <Func <TModel, TValue> > expression,
                                                                      int tabIndex          = 0,
                                                                      bool readOnly         = false,
                                                                      string sClass         = null,
                                                                      object HtmlAttributes = null)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            RouteValueDictionary oHtmlAttributes = new RouteValueDictionary(HtmlAttributes);

            if (!string.IsNullOrEmpty(metadata.Description))
            {
                oHtmlAttributes.Add("title", metadata.Description);
            }
            if (tabIndex != 0 && !oHtmlAttributes.ContainsKey("tabindex"))
            {
                oHtmlAttributes.Add("tabindex", tabIndex);
            }
            if (readOnly && !oHtmlAttributes.ContainsKey("readonly"))
            {
                oHtmlAttributes.Add("readonly", "1");
            }

            // Obtenemos la información utilizada para validar el tamaño del texto
            ControllerContext            cctx = htmlHelper.ViewContext.Controller.ControllerContext;
            StringLengthAttributeAdapter stringLengthValidator = metadata.GetValidators(cctx)
                                                                 .OfType <StringLengthAttributeAdapter>( )
                                                                 .FirstOrDefault( );

            if (stringLengthValidator != null)                                 // Si hay validación de este tipo...
            {
                var parms = stringLengthValidator.GetClientValidationRules( )
                            .First( )
                            .ValidationParameters;
                // Obtenemos el valor
                int maxlength = (int)parms["max"];                    // tamaño máximo para el texto...

                oHtmlAttributes.Add("maxlength", maxlength);          // y añadimos el atributo maxlength
            }

            if (!string.IsNullOrEmpty(sClass))
            {
                oHtmlAttributes.Add("class", sClass);
            }

            return(Html.InputExtensions.TextBoxFor(htmlHelper, expression, oHtmlAttributes));
        }
Beispiel #4
0
        /// <summary>
        /// Text Area
        /// El title y el maxlenght se obtiene del Metadata
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="NumRows"></param>
        /// <param name="sClass"></param>
        /// <param name="HtmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString HelpTextAreaFor <TModel, TValue>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, TValue> > expression,
            int NumRows,                // Obligatorio
            string sClass         = null,
            object HtmlAttributes = null)
        {
            if (NumRows < 1)
            {
                throw new ArgumentNullException("NumRows");
            }
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            RouteValueDictionary routeValues = new RouteValueDictionary(HtmlAttributes);

            if (!string.IsNullOrEmpty(metadata.Description))
            {
                routeValues.Add("title", metadata.Description);
            }

            // Obtenemos la información utilizada para validar el tamaño del texto
            ControllerContext            cctx = htmlHelper.ViewContext.Controller.ControllerContext;
            StringLengthAttributeAdapter stringLengthValidator = metadata.GetValidators(cctx)
                                                                 .OfType <StringLengthAttributeAdapter>( )
                                                                 .FirstOrDefault( );

            if (stringLengthValidator != null)                                                              // Si hay validación de este tipo...
            {
                var parms = stringLengthValidator.GetClientValidationRules( )
                            .First( )
                            .ValidationParameters;
                // Obtenemos el valor
                int maxlength = (int)parms["max"];                    // tamaño máximo para el texto...

                routeValues.Add("maxlength", maxlength);              // y añadimos el atributo maxlength
                routeValues.Add("onkeyup", "return EVENT.onTextAreaMaxLen(this)");
            }
            routeValues.Add("rows", Convert.ToString(NumRows));

            if (!string.IsNullOrEmpty(sClass))
            {
                routeValues.Add("class", sClass);
            }

            return(Html.TextAreaExtensions.TextAreaFor(htmlHelper, expression, routeValues));
        }
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <param name="sClass"></param>
        /// <param name="HtmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString HelpInputNumericFor <TModel, TValue>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, TValue> > expression,
            string sClass         = null,
            object HtmlAttributes = null)
        {
            RouteValueDictionary routeValues = new RouteValueDictionary(HtmlAttributes);

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            if (!string.IsNullOrEmpty(metadata.Description))
            {
                routeValues.Add("title", metadata.Description);
            }

            // Obtenemos la información utilizada para validar el tamaño del texto
            ControllerContext            cctx = htmlHelper.ViewContext.Controller.ControllerContext;
            StringLengthAttributeAdapter stringLengthValidator = metadata.GetValidators(cctx)
                                                                 .OfType <StringLengthAttributeAdapter>( )
                                                                 .FirstOrDefault( );

            if (stringLengthValidator != null)                                                              // Si hay validación de este tipo...
            {
                var parms = stringLengthValidator.GetClientValidationRules( )
                            .First( )
                            .ValidationParameters;
                // Obtenemos el valor
                int maxlength = (int)parms["max"];                    // tamaño máximo para el texto...

                routeValues.Add("maxlength", maxlength);              // y añadimos el atributo maxlength
            }

            routeValues.Add("onkeypress", "F.Validate.Event.PressOnlyNumbers(event)");

            if (!string.IsNullOrEmpty(sClass))
            {
                routeValues.Add("class", sClass);
            }
            else
            {
                routeValues.Add("class", "Helper-InputTextBoxNumeric");
            }

            return(Html.InputExtensions.TextBoxFor(htmlHelper, expression, routeValues));
        }
        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = new DataAnnotationsModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(() => null, typeof(string), "Length");
            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(attribute);
            var context = new ClientModelValidationContext(metadata, provider);

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

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal("The field Length must be a string with a maximum length of 8.",
                         rule.ErrorMessage);
        }
        public void ClientRulesWithStringLengthAttribute() {
            // Arrange
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), "Length");
            var context = new ControllerContext();
            var attribute = new StringLengthAttribute(10);
            var adapter = new StringLengthAttributeAdapter(metadata, context, attribute);

            // Act
            var rules = adapter.GetClientValidationRules()
                               .OrderBy(r => r.ValidationType)
                               .ToArray();

            // Assert
            Assert.AreEqual(1, rules.Length);

            Assert.AreEqual("stringLength", rules[0].ValidationType);
            Assert.AreEqual(2, rules[0].ValidationParameters.Count);
            Assert.AreEqual(0, rules[0].ValidationParameters["minimumLength"]);
            Assert.AreEqual(10, rules[0].ValidationParameters["maximumLength"]);
            Assert.AreEqual(@"The field Length must be a string with a maximum length of 10.", rules[0].ErrorMessage);
        }
        public void GetClientValidationRules_WithMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(attribute);
            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("length", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(8, rule.ValidationParameters["max"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }
        public void GetClientValidationRules_WithMinAndMaxLength_ReturnsValidationParameters()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(10) { MinimumLength = 3 };
            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null);

            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("length", rule.ValidationType);
            Assert.Equal(2, rule.ValidationParameters.Count);
            Assert.Equal(3, rule.ValidationParameters["min"]);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal(attribute.FormatErrorMessage("Length"), rule.ErrorMessage);
        }