Esempio n. 1
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var elementName    = context.Attributes["name"];
            var attributeValue = $"aspnet:{elementName}";

            // Special handling for required rule. Needs to be a part of the base rule definition
            // of the v-validate attribute
            var isRequired = context.Attributes.ContainsKey("data-val-required");

            attributeValue = isRequired ? $"required|{attributeValue}" : attributeValue;

            MergeAttribute(context.Attributes, "v-validate", $"'{attributeValue}'");
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    regexVal  = (RegularExpressionValidator)Validator;
            var    formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            string messageTemplate;

            try {
                messageTemplate = regexVal.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                messageTemplate = Messages.regex_error;
            }
            string message = formatter.BuildMessage(messageTemplate);

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-regex", message);
            MergeAttribute(context.Attributes, "data-val-regex-pattern", regexVal.Expression);
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());

            string messageTemplate;

            try {
                messageTemplate = EmailValidator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                messageTemplate = ValidatorOptions.LanguageManager.GetStringForValidator <EmailValidator>();
            }

            string message = formatter.BuildMessage(messageTemplate);

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-email", message);
        }
        /// <summary>
        /// クライアントでのバリデーション用の操作
        /// </summary>
        /// <param name="context">クライアントのバリデーションコンテキスト</param>
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // 以下のタグ属性を設定する
            // required                         "required"
            // notupported-required-err-msg     未サポートブラウザでのエラーメッセージ
            // required-err-msg                 バリデーションで設定されたエラーメッセージ
            MergeAttribute(context.Attributes, "required", "required");
            MergeAttribute(context.Attributes, "notsupported-required-err-msg", context.ModelMetadata.DisplayName + "は入力必須です。");
            if (!string.IsNullOrWhiteSpace(ErrorMessage))
            {
                MergeAttribute(context.Attributes, "required-err-msg", ErrorMessage);
            }
        }
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("ComparisonValue", RangeValidator.ValueToCompare);

            string message;

            try {
                message = RangeValidator.Options.ErrorMessageSource.GetString(null);
            } catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetStringForValidator <LessThanOrEqualValidator>();
            }

            message = formatter.BuildMessage(message);

            return(message);
        }
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var    formatter = ValidatorOptions.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string messageTemplate;

            try
            {
                messageTemplate = Validator.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException)
            {
                messageTemplate = ValidatorOptions.LanguageManager.GetStringForValidator <NotEmptyValidator>();
            }

            var message = formatter.BuildMessage(messageTemplate);

            return(message);
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var smt      = (Microsoft.AspNetCore.Mvc.Rendering.ViewContext)context.ActionContext;
            var property = context.ModelMetadata.ContainerType.GetProperty(Attribute.PropertyName);

            var model = smt.ViewData.ModelExplorer.Container.Model;

            var typeProperty  = context.ModelMetadata.ContainerType.GetProperty(property.Name);
            var propertyValue = typeProperty?.GetValue(smt.ViewData.ModelExplorer.Container.Model, null);

            if (propertyValue?.GetType() == typeof(bool) && (bool)propertyValue != true)
            {
                return;
            }

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-required", GetErrorMessage(context));
        }
Esempio n. 8
0
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            string propertyDisplayName = context.ModelMetadata.GetDisplayName();
            var    errorMessage        = FormatErrorMessage(propertyDisplayName);

            AddAttribute(context.Attributes, "data-val", "true");
            AddAttribute(context.Attributes, "data-val-valid-date-format", "The input date/datetime format is not valid! Please prefer: '01-Jan-2019' format.");
            AddAttribute(context.Attributes, "data-val-mindate", errorMessage);

            var minDate = MinDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);

            AddAttribute(context.Attributes, "data-val-mindate-date", minDate);
        }
Esempio n. 9
0
        private static IDictionary <string, object> GetUnobtrusiveValidationAttributes(PropertyInfo propertyInfo, ModelMetadata modelMetadata, IModelMetadataProvider provider)
        {
            var hasRequiredAttribute = false;
            var propType             = GetPropertyType(propertyInfo);
            var attrs = new AttributeDictionary();

            var valAttrs = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute));

            ValidationAttributeAdapterProvider adapterProvider = new ValidationAttributeAdapterProvider();
            IAttributeAdapter adapter;

            var context = new ClientModelValidationContext(
                new ActionContext(),
                modelMetadata,
                provider,
                attrs);

            foreach (ValidationAttribute valAttr in valAttrs)
            {
                if (valAttr is RequiredAttribute)
                {
                    hasRequiredAttribute = true;
                }

                adapter = adapterProvider.GetAttributeAdapter(valAttr, null);
                adapter.AddValidation(context);
            }

            if (!hasRequiredAttribute && context.ModelMetadata.IsRequired)
            {
                adapter = adapterProvider.GetAttributeAdapter(new RequiredAttribute(), null);
                adapter.AddValidation(context);
            }

            if (propType == typeof(float) ||
                propType == typeof(double) ||
                propType == typeof(decimal))
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                MergeAttribute(context.Attributes, "data-val-number", GetErrorMessage(context.ModelMetadata));
            }

            return(attrs.ToDictionary(p => p.Key, pp => (object)pp.Value));
        }
        private string GetErrorMessage(LengthValidator lengthVal, ClientModelValidationContext context)
        {
            var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();

            var formatter = cfg.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", lengthVal.Min)
                            .AppendArgument("MaxLength", lengthVal.Max);

            bool needsSimplifiedMessage = lengthVal.Options.ErrorMessageSource is LanguageStringSource;

            string message;

            try {
                message = lengthVal.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                if (lengthVal is ExactLengthValidator)
                {
                    message = cfg.LanguageManager.GetString("ExactLength_Simple");
                }
                else
                {
                    message = cfg.LanguageManager.GetString("Length_Simple");
                }

                needsSimplifiedMessage = false;
            }

            if (needsSimplifiedMessage && message.Contains("{TotalLength}"))
            {
                if (lengthVal is ExactLengthValidator)
                {
                    message = cfg.LanguageManager.GetString("ExactLength_Simple");
                }
                else
                {
                    message = cfg.LanguageManager.GetString("Length_Simple");
                }
            }

            message = formatter.BuildMessage(message);
            return(message);
        }
        /// <summary>
        ///     Provides unique validation type within current annotated field range, when multiple annotations are used (required for client-side).
        /// </summary>
        /// <param name="baseName">Base name.</param>
        /// <returns>
        ///     Unique validation type within current request.
        /// </returns>
        private string GetUniqueValidationId(ClientModelValidationContext context)
        {
            const int UtfCodeLetterA = 97; //utf code for the first lowercase letter

            var baseName = GetBasicRuleType();

            string suffix = "";

            var count = 0;

            while (context?.Attributes != null && context.Attributes.ContainsKey($"data-val-{baseName}{suffix}"))
            {
                AssertAttribsQuantityAllowed(count);
                suffix = char.ConvertFromUtf32(UtfCodeLetterA + count); // single lowercase letter from latin alphabet
                count++;
            }

            return($"{baseName}{suffix}");
        }
        /// <summary>
        /// Adds a client validation rule
        /// </summary>
        /// <param name="context"></param>
        protected override void AddClientValidation(ClientModelValidationContext context)
        {
            var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            var message   = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());

            string max = Convert.ToString(MaxValue, CultureInfo.InvariantCulture);
            string min = Convert.ToString(MinValue, CultureInfo.InvariantCulture);

            MergeClientAttribute(context, "data-val", "true");
            MergeClientAttribute(context, "data-val-range", message);
            if (!string.IsNullOrWhiteSpace(min))
            {
                MergeClientAttribute(context, "data-val-range-min", min);
            }
            if (!string.IsNullOrWhiteSpace(max))
            {
                MergeClientAttribute(context, "data-val-range-max", max);
            }
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    cfg       = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
            var    regexVal  = (RegularExpressionValidator)Validator;
            var    formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string messageTemplate;

            try {
                messageTemplate = regexVal.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                messageTemplate = cfg.LanguageManager.GetStringForValidator <RegularExpressionValidator>();
            }
            string message = formatter.BuildMessage(messageTemplate);

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-regex", message);
            MergeAttribute(context.Attributes, "data-val-regex-pattern", regexVal.Expression);
        }
Esempio n. 14
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var cfg       = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
            var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));

            string messageTemplate;

            try {
                messageTemplate = Component.GetUnformattedErrorMessage();
            }
            catch (NullReferenceException) {
                messageTemplate = cfg.LanguageManager.GetString("EmailValidator");
            }

            string message = formatter.BuildMessage(messageTemplate);

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-email", message);
        }
Esempio n. 15
0
        private void CheckForLocalizer(ClientModelValidationContext context)
        {
            if (!_checkedForLocalizer)
            {
                _checkedForLocalizer = true;

                var services = context.ActionContext.HttpContext.RequestServices;
                var options  = services.GetRequiredService <IOptions <MvcDataAnnotationsLocalizationOptions> >();
                var factory  = services.GetService <IStringLocalizerFactory>();

                var provider = options.Value.DataAnnotationLocalizerProvider;
                if (factory != null && provider != null)
                {
                    _stringLocalizer = provider(
                        context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType,
                        factory);
                }
            }
        }
Esempio n. 16
0
        public void AddValidation(ClientModelValidationContext context)
        {
            throw new System.NotImplementedException();

            /*
             *
             * FormulaireViewModel formulaireViewModel = validationContext.ObjectInstance as FormulaireViewModel;
             *
             *
             * string linkPropertyValue = formulaireViewModel.GetType().GetProperty(PropertyName).GetValue(formulaireViewModel).ToString();
             *
             * if (formulaireViewModel == null)
             *  return ValidationResult.Success;
             *
             * return new ValidationResult("Message");
             *
             *
             */
        }
Esempio n. 17
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    cfg       = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
            var    formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
            string message;

            try {
                message = Validator.Options.GetErrorMessageTemplate(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = cfg.LanguageManager.GetStringForValidator <CreditCardValidator>();
            }
            catch (NullReferenceException) {
                message = cfg.LanguageManager.GetStringForValidator <CreditCardValidator>();
            }
            message = formatter.BuildMessage(message);
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-creditcard", message);
        }
        public override void AddValidationAttributes(ViewContext viewContext, ModelExplorer modelExplorer, IDictionary <string, string> attributes)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException(nameof(viewContext));
            }

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

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

            var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null;

            if (formContext == null)
            {
                return;
            }

            var validators = ((CustomClientValidatorCache)_clientValidatorCache).GetValidatorsWithoutCache(
                modelExplorer.Metadata,
                _clientModelValidatorProvider);

            if (validators.Count > 0)
            {
                var validationContext = new ClientModelValidationContext(
                    viewContext,
                    modelExplorer.Metadata,
                    _metadataProvider,
                    attributes);

                for (var i = 0; i < validators.Count; i++)
                {
                    var validator = validators[i];
                    validator.AddValidation(validationContext);
                }
            }
        }
Esempio n. 19
0
        private string GetErrorMessage(LengthValidator lengthVal, ClientModelValidationContext context)
        {
            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", lengthVal.Min)
                            .AppendArgument("MaxLength", lengthVal.Max);

            var messageNeedsSplitting = lengthVal.ErrorMessageSource.ResourceType == typeof(LanguageManager);

            string message;

            try
            {
                message = lengthVal.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException)
            {
                if (lengthVal is ExactLengthValidator)
                {
                    message = ValidatorOptions.LanguageManager.GetStringForValidator <ExactLengthValidator>();
                }
                else
                {
                    message = ValidatorOptions.LanguageManager.GetStringForValidator <LengthValidator>();
                }

                messageNeedsSplitting = true;
            }

            if (messageNeedsSplitting)
            {
                // If we're using the default resources then the mesage for length errors will have two parts, eg:
                // '{PropertyName}' must be between {MinLength} and {MaxLength} characters. You entered {TotalLength} characters.
                // We can't include the "TotalLength" part of the message because this information isn't available at the time the message is constructed.
                // Instead, we'll just strip this off by finding the index of the period that separates the two parts of the message.

                message = message.Substring(0, message.IndexOf(".") + 1);
            }

            message = formatter.BuildMessage(message);
            return(message);
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            SetupValidator(context.ModelMetadata);

            var validationId          = GetUniqueValidationId(context);
            var formattedErrorMessage = GetErrorMessage(context);

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, $"data-val-{validationId}", formattedErrorMessage);

            MergeExpressiveAttribute(context, validationId, "expression", Attribute.Expression);

            if (AllowEmpty.HasValue)
            {
                MergeExpressiveAttribute(context, validationId, "allowempty", AllowEmpty);
            }

            if (FieldsMap != null && FieldsMap.Any())
            {
                MergeExpressiveAttribute(context, validationId, "fieldsmap", FieldsMap);
            }
            if (ConstsMap != null && ConstsMap.Any())
            {
                MergeExpressiveAttribute(context, validationId, "constsmap", ConstsMap);
            }
            if (EnumsMap != null && EnumsMap.Any())
            {
                MergeExpressiveAttribute(context, validationId, "enumsmap", EnumsMap);
            }
            if (MethodsList != null && MethodsList.Any())
            {
                MergeExpressiveAttribute(context, validationId, "methodslist", MethodsList);
            }
            if (ParsersMap != null && ParsersMap.Any())
            {
                MergeExpressiveAttribute(context, validationId, "parsersmap", ParsersMap);
            }
            if (ErrFieldsMap != null && ErrFieldsMap.Any())
            {
                MergeExpressiveAttribute(context, validationId, "errfieldsmap", ErrFieldsMap);
            }
        }
Esempio n. 21
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var modelType         = context.ModelMetadata.ContainerType;
            var otherPropertyInfo = modelType.GetProperty(Attribute.OtherPropertyName);

            if (otherPropertyInfo == null)
            {
                throw new ApplicationException($"Model does not contain any property named {Attribute.OtherPropertyName}");
            }

            var otherPropertyType = otherPropertyInfo.PropertyType;

            if (otherPropertyType.IsDateTimeType())
            {
                AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "datetime");
            }
            else if (otherPropertyType.IsNumericType())
            {
                AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "number");
            }
            else if (otherPropertyType == typeof(string))
            {
                AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "string");
            }
            else if (otherPropertyType.IsTimeSpanType())
            {
                AddAttribute(context.Attributes, "data-val-requiredif-other-property-type", "timespan");
            }
            else
            {
                throw new ApplicationException($"This attribute does not support type {otherPropertyType}");
            }

            AddAttribute(context.Attributes, "data-val", "true");
            AddAttribute(context.Attributes, "data-val-requiredif-other-property", Attribute.OtherPropertyName);
            AddAttribute(context.Attributes, "data-val-requiredif-comparison-type", Attribute.ComparisonType.ToString());
            AddAttribute(context.Attributes, "data-val-requiredif-other-property-value", Attribute.OtherPropertyValue?.ToString() ?? string.Empty);

            string errorMessage = GetErrorMessage(context);

            AddAttribute(context.Attributes, "data-val-requiredif", errorMessage);
        }
Esempio n. 22
0
        protected override string GetUrl(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var services  = context.ActionContext.HttpContext.RequestServices;
            var factory   = services.GetRequiredService <IUrlHelperFactory>();
            var urlHelper = factory.GetUrlHelper(context.ActionContext);

            var url = urlHelper.Page(PageName, PageHandler, RouteData);

            if (url == null)
            {
                throw new InvalidOperationException(Resources.RemoteAttribute_NoUrlFound);
            }

            return(url);
        }
Esempio n. 23
0
        /// <inheritdoc />
        public override void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-length", GetErrorMessage(context));

            if (Attribute.MaximumLength != int.MaxValue)
            {
                MergeAttribute(context.Attributes, "data-val-length-max", _max);
            }

            if (Attribute.MinimumLength != 0)
            {
                MergeAttribute(context.Attributes, "data-val-length-min", _min);
            }
        }
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var    cfg       = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
            var    formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName(null));
            string messageTemplate;

            try {
                messageTemplate = Validator.Options.GetErrorMessageTemplate(null);
            }
            catch (FluentValidationMessageFormatException) {
                messageTemplate = cfg.LanguageManager.GetStringForValidator <NotEmptyValidator>();
            }
            catch (NullReferenceException) {
                messageTemplate = cfg.LanguageManager.GetStringForValidator <NotEmptyValidator>();
            }

            var message = formatter.BuildMessage(messageTemplate);

            return(message);
        }
Esempio n. 25
0
 public void AddValidation(ClientModelValidationContext context)
 {
     if (string.IsNullOrWhiteSpace(targetDisplayName))
     {
         targetDisplayName = context.ModelMetadata.DisplayName ?? context.ModelMetadata.Name;
     }
     if (context.Attributes != null)
     {
         context.Attributes[DataValidationAttributeKey]         = true.ToString().ToLower();
         context.Attributes[DataValidationRequiredAttributeKey] = string
                                                                  .Format(StringBlankErrorMessage, targetDisplayName);
         context.Attributes[DataValidationMaxLengthAttributeKey] = UsernameMaxLength.ToString();
         context.Attributes[DataValidationMinLengthAttributeKey] = UsernameMinLength.ToString();
         context.Attributes[DataValidationLengthAttributeKey]    = string
                                                                   .Format(StringLengthErrorMessage, targetDisplayName, UsernameMaxLength, UsernameMinLength);
         context.Attributes[DataValidationRegexPatternAttributeKey] = UsernamePattern;
         context.Attributes[DataValidationRegexAttributeKey]        = string
                                                                      .Format(FormatMismatchErrorMessage, targetDisplayName);
     }
 }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var cfg       = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();
            var formatter = cfg.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());

            string messageTemplate;

            try {
                messageTemplate = Validator.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
#pragma warning disable 618
                messageTemplate = cfg.LanguageManager.GetStringForValidator <EmailValidator>();
#pragma warning restore 618
            }

            string message = formatter.BuildMessage(messageTemplate);
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-email", message);
        }
Esempio n. 27
0
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Attributes.ContainsKey("class") && context.Attributes["class"].ContainsSwedish("force-validation"))
            {
                var minText = Min != 0 ? $"minst {Min} val" : "";
                var maxText = Max != int.MaxValue ? $"max {Max} val" : "";
                var bridge  = Min != 0 && Max != int.MaxValue ? " och " : "";

                MergeAttribute(context.Attributes, "data-val", "true");
                MergeAttribute(context.Attributes, "data-val-requiredchecked", $"{context.ModelMetadata.DisplayName} måste ha {minText}{bridge}{maxText} ifyllt");
                MergeAttribute(context.Attributes, "data-val-requiredchecked-min", Min.ToSwedishString());
                MergeAttribute(context.Attributes, "data-val-requiredchecked-max", Max.ToSwedishString());
                MergeAttribute(context.Attributes, "data-val-requiredchecked-maxchecked", int.MaxValue.ToSwedishString());
            }
        }
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();

            var formatter = cfg.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("ComparisonValue", RangeValidator.ValueToCompare);

            string message;

            try {
                message = RangeValidator.Options.ErrorMessageSource.GetString(null);
            } catch (FluentValidationMessageFormatException) {
                message = cfg.LanguageManager.GetStringForValidator <GreaterThanOrEqualValidator>();
            }

            message = formatter.BuildMessage(message);

            return(message);
        }
Esempio n. 29
0
    public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
    {
        // Arrange
        var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
        var metadata         = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

        var attribute = new CompareAttribute("OtherProperty");

        attribute.ErrorMessage = "CompareAttributeErrorMessage";

        var stringLocalizer    = new Mock <IStringLocalizer>();
        var expectedProperties = new object[] { "MyPropertyDisplayName", "OtherPropertyDisplayName" };

        var expectedMessage = "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.";

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

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

        var actionContext = new ActionContext();
        var context       = new ClientModelValidationContext(
            actionContext,
            metadata,
            metadataProvider,
            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-equalto", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); },
            kvp =>
        {
            Assert.Equal("data-val-equalto-other", kvp.Key);
            Assert.Equal("*.OtherProperty", kvp.Value);
        });
    }
        private string GetErrorMessage(ILengthValidator lengthVal, ClientModelValidationContext context)
        {
            var cfg = context.ActionContext.HttpContext.RequestServices.GetValidatorConfiguration();

            var formatter = cfg.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName(null))
                            .AppendArgument("MinLength", lengthVal.Min)
                            .AppendArgument("MaxLength", lengthVal.Max);

            string message;

            try {
                message = Component.GetUnformattedErrorMessage();
            }
            catch (NullReferenceException) {
                if (lengthVal is IExactLengthValidator)
                {
                    message = cfg.LanguageManager.GetString("ExactLength_Simple");
                }
                else
                {
                    message = cfg.LanguageManager.GetString("Length_Simple");
                }
            }


            if (message.Contains("{TotalLength}"))
            {
                if (lengthVal is IExactLengthValidator)
                {
                    message = cfg.LanguageManager.GetString("ExactLength_Simple");
                }
                else
                {
                    message = cfg.LanguageManager.GetString("Length_Simple");
                }
            }

            message = formatter.BuildMessage(message);
            return(message);
        }