Example #1
0
    public void AddValidation_WithMaxLengthAndMinLength_AddsAttributes_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 and not shorter than '{2}' characters.";

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

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

        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, 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-length", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
            kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("8", kvp.Value); });
    }
        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);
        }
        public void AddValidation_DoesNotTrounceExistingAttributes()
        {
            // 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 expectedMessage = attribute.FormatErrorMessage("Length");

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

            context.Attributes.Add("data-val", "original");
            context.Attributes.Add("data-val-length", "original");
            context.Attributes.Add("data-val-length-max", "original");
            context.Attributes.Add("data-val-length-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-length", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("original", kvp.Value); },
                kvp => { Assert.Equal("data-val-length-min", kvp.Key); Assert.Equal("original", kvp.Value); });
        }
        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);
        }
Example #5
0
    public void AddValidation_WithMinAndMaxLength_AddsAttributes()
    {
        // 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 expectedMessage = attribute.FormatErrorMessage("Length");

        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-length", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
            kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("10", kvp.Value); },
            kvp => { Assert.Equal("data-val-length-min", kvp.Key); Assert.Equal("3", kvp.Value); });
    }
        /// <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));
        }
Example #7
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));
        }
        public void AddValidation_adds_max_rule()
        {
            // Arrange
            var attribute = new StringLengthAttribute(10);
            var adapter   = new StringLengthAttributeAdapter(attribute);

            var context = new ClientModelValidationContextBuilder()
                          .WithModelType <string>()
                          .Build();

            // Act
            adapter.AddValidation(context);

            // Assert
            context.Attributes.Keys.ShouldContain("v-validate");
            context.Attributes["v-validate"].ShouldBe("{max:10}");
        }
        /// <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 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 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_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);
        }
        public void AddValidation_WithMaxLength_AddsAttributes()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");

            var attribute = new StringLengthAttribute(8);
            var adapter = new StringLengthAttributeAdapter(attribute, stringLocalizer: null);

            var expectedMessage = attribute.FormatErrorMessage("Length");

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

            // 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-length", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("8", kvp.Value); });
        }
        public void AddValidation_WithMaxLength_AddsAttributes_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, new AttributeDictionary());

            // 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-length", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
                kvp => { Assert.Equal("data-val-length-max", kvp.Key); Assert.Equal("8", kvp.Value); });
        }
Example #16
0
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            IAttributeAdapter adapter;

            var type = attribute.GetType();

            if (type == typeof(RegularExpressionAttribute))
            {
                adapter = new RegularExpressionAttributeAdapter((RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MaxLengthAttribute))
            {
                adapter = new MaxLengthAttributeAdapter((MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RequiredAttribute))
            {
                adapter = new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CompareAttribute))
            {
                adapter = new CompareAttributeAdapter((CompareAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MinLengthAttribute))
            {
                adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CreditCardAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-creditcard", stringLocalizer);
            }
            else if (type == typeof(StringLengthAttribute))
            {
                adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RangeAttribute))
            {
                adapter = new RangeAttributeAdapterExt((RangeAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(DynamicRangeAttribute))
            {
                adapter = new DynamicRangeAttributeAdapter((DynamicRangeAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(EmailAddressAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-email", stringLocalizer);
            }
            else if (type == typeof(PhoneAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-phone", stringLocalizer);
            }
            else if (type == typeof(UrlAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-url", stringLocalizer);
            }
            else
            {
                adapter = null;
            }

            return(adapter);
        }
Example #17
0
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            if (_options == null)
            {
                throw new ArgumentNullException(nameof(_options));
            }

            IAttributeAdapter adapter;

            if (attribute is CompareAttribute compareAttribute)
            {
                adapter = new CompareAttributeAdapter(compareAttribute);
            }
            else if (attribute is CreditCardAttribute creditCardAttribute)
            {
                adapter = new CreditCardAttributeAdapter(creditCardAttribute);
            }
            else if (attribute is EmailAddressAttribute emailAddressAttribute)
            {
                adapter = new EmailAddressAttributeAdapter(emailAddressAttribute);
            }
            else if (attribute is FileExtensionsAttribute fileExtensionsAttribute)
            {
                adapter = new FileExtensionsAttributeAdapter(fileExtensionsAttribute);
            }
            else if (attribute is MaxLengthAttribute maxLengthAttribute)
            {
                adapter = new MaxLengthAttributeAdapter(maxLengthAttribute);
            }
            else if (attribute is MinLengthAttribute minLengthAttribute)
            {
                adapter = new MinLengthAttributeAdapter(minLengthAttribute);
            }
            else if (attribute is RangeAttribute rangeAttribute)
            {
                adapter = new RangeAttributeAdapter(rangeAttribute, _options);
            }
            else if (attribute is RegularExpressionAttribute regularExpressionAttribute)
            {
                adapter = new RegularExpressionAttributeAdapter(regularExpressionAttribute);
            }
            else if (attribute is RequiredAttribute requiredAttribute)
            {
                adapter = new RequiredAttributeAdapter(requiredAttribute);
            }
            else if (attribute is StringLengthAttribute stringLengthAttribute)
            {
                adapter = new StringLengthAttributeAdapter(stringLengthAttribute);
            }
            else if (attribute is UrlAttribute urlAttribute)
            {
                adapter = new UrlAttributeAdapter(urlAttribute);
            }
            else
            {
                adapter = null;
            }

            return(adapter);
        }
Example #18
0
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            IAttributeAdapter adapter = null;

            var type = attribute.GetType();

#if NETCOREAPP2_2
            if (attribute is RegularExpressionAttribute)
            {
                adapter = new RegularExpressionAttributeAdapter((RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MaxLengthAttribute)
            {
                adapter = new MaxLengthAttributeAdapter((MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RequiredAttribute)
            {
                adapter = new Microsoft.AspNetCore.Mvc.DataAnnotations.Internal.RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CompareAttribute)
            {
                adapter = new CompareAttributeAdapter((CompareAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MinLengthAttribute)
            {
                adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CreditCardAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-creditcard", stringLocalizer);
            }
            else if (attribute is StringLengthAttribute)
            {
                adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RangeAttribute)
            {
                adapter = new RangeAttributeAdapter((RangeAttribute)attribute, stringLocalizer);
            }
            else if (attribute is EmailAddressAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-email", stringLocalizer);
            }
            else if (attribute is PhoneAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-phone", stringLocalizer);
            }
            else if (attribute is UrlAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-url", stringLocalizer);
            }
            else if (attribute is FileExtensionsAttribute)
            {
                adapter = new FileExtensionsAttributeAdapter((FileExtensionsAttribute)attribute, stringLocalizer);
            }
            else
            {
                adapter = defaultClientModelValidatorProvider.GetAttributeAdapter(attribute, stringLocalizer);
            }
#else
            if (attribute is RegularExpressionAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.RegularExpressionAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MaxLengthAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.MaxLengthAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RequiredAttribute)
            {
                adapter = new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CompareAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.CompareAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (CompareAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MinLengthAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.MinLengthAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CreditCardAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.DataTypeAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (DataTypeAttribute)attribute, "data-val-creditcard", stringLocalizer);
            }
            else if (attribute is StringLengthAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.StringLengthAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RangeAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.RangeAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (RangeAttribute)attribute, stringLocalizer);
            }
            else if (attribute is EmailAddressAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.DataTypeAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (DataTypeAttribute)attribute, "data-val-email", stringLocalizer);
            }
            else if (attribute is PhoneAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.DataTypeAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (DataTypeAttribute)attribute, "data-val-phone", stringLocalizer);
            }
            else if (attribute is UrlAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.DataTypeAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (DataTypeAttribute)attribute, "data-val-url", stringLocalizer);
            }
            else if (attribute is FileExtensionsAttribute)
            {
                adapter = (IAttributeAdapter)Activator.CreateInstance(Type.GetType("Microsoft.AspNetCore.Mvc.DataAnnotations.FileExtensionsAttributeAdapter, Microsoft.AspNetCore.Mvc.DataAnnotations"), (FileExtensionsAttribute)attribute, stringLocalizer);
            }
            else
            {
                adapter = defaultClientModelValidatorProvider.GetAttributeAdapter(attribute, stringLocalizer);
            }
#endif

            return(adapter);
        }
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            IAttributeAdapter adapter;

            var type = attribute.GetType();

            if (attribute is RegularExpressionAttribute)
            {
                adapter = new RegularExpressionAttributeAdapter((RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MaxLengthAttribute)
            {
                adapter = new MaxLengthAttributeAdapter((MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RequiredAttribute)
            {
                adapter = new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CompareAttribute)
            {
                adapter = new CompareAttributeAdapter((CompareAttribute)attribute, stringLocalizer);
            }
            else if (attribute is MinLengthAttribute)
            {
                adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is CreditCardAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-creditcard", stringLocalizer);
            }
            else if (attribute is StringLengthAttribute)
            {
                adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (attribute is RangeAttribute)
            {
                adapter = new RangeAttributeAdapter((RangeAttribute)attribute, stringLocalizer);
            }
            else if (attribute is EmailAddressAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-email", stringLocalizer);
            }
            else if (attribute is PhoneAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-phone", stringLocalizer);
            }
            else if (attribute is UrlAttribute)
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "data-val-url", stringLocalizer);
            }
            else if (attribute is FileExtensionsAttribute)
            {
                adapter = new FileExtensionsAttributeAdapter((FileExtensionsAttribute)attribute, stringLocalizer);
            }
            else
            {
                adapter = defaultClientModelValidatorProvider.GetAttributeAdapter(attribute, stringLocalizer);
            }

            return(adapter);
        }
        /// <summary>
        /// Creates an <see cref="IAttributeAdapter"/> for the given attribute.
        /// </summary>
        /// <param name="attribute">The attribute to create an adapter for.</param>
        /// <param name="stringLocalizer">The localizer to provide to the adapter.</param>
        /// <returns>An <see cref="IAttributeAdapter"/> for the given attribute.</returns>
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            IAttributeAdapter adapter;

            var type = attribute.GetType();

            if (type == typeof(RegularExpressionAttribute))
            {
                adapter = new RegularExpressionAttributeAdapter((RegularExpressionAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MaxLengthAttribute))
            {
                adapter = new MaxLengthAttributeAdapter((MaxLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RequiredAttribute))
            {
                adapter = new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CompareAttribute))
            {
                adapter = new CompareAttributeAdapter((CompareAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(MinLengthAttribute))
            {
                adapter = new MinLengthAttributeAdapter((MinLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(CreditCardAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "creditcard", stringLocalizer);
            }
            else if (type == typeof(StringLengthAttribute))
            {
                adapter = new StringLengthAttributeAdapter((StringLengthAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(RangeAttribute))
            {
                adapter = new RangeAttributeAdapter((RangeAttribute)attribute, stringLocalizer);
            }
            else if (type == typeof(EmailAddressAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "email", stringLocalizer);
            }
            else if (type == typeof(PhoneAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "phone", stringLocalizer);
            }
            else if (type == typeof(UrlAttribute))
            {
                adapter = new DataTypeAttributeAdapter((DataTypeAttribute)attribute, "url", stringLocalizer);
            }
            else
            {
                adapter = null;
            }

            return adapter;
        }