/// <summary>
        /// Get a error message for a property
        /// </summary>
        /// <param name="propertyValidator">PropertyValidator to get for</param>
        /// <param name="propertyName">Name of propery</param>
        /// <returns>Formatted string</returns>
        public static string GetErrorMessageFor(this IPropertyValidator propertyValidator, string propertyName)
        {
            var formatter = new MessageFormatter().AppendPropertyName(propertyName);

#if (NET461)
            var errorMessage = formatter.BuildMessage(propertyValidator.ErrorMessageSource.GetString(null));
#else
            var errorMessage = formatter.BuildMessage(propertyValidator.ErrorMessageSource.GetString());
#endif
            return(errorMessage);
        }
Esempio n. 2
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var propertyToCompare = ActiveAndStatusMatchValidator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(Rule.GetDisplayName())
                                .AppendArgument("PropertyNameTo", comparisonDisplayName);

                string message = formatter.BuildMessage(ActiveAndStatusMatchValidator.ErrorMessageSource.GetString());

                var rule = new ModelClientValidationRule
                {
                    ErrorMessage   = message,               // default error message
                    ValidationType = "activeandstatusmatch" // name of the validatoin which will be used inside unobtrusive library
                };

                rule.ValidationParameters["comparewith"] = propertyToCompare.Name; // html element which includes prefix information
                yield return(rule);
            }
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            var    formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
            string message   = formatter.BuildMessage(RegexValidator.ErrorMessageSource.GetString());

            yield return(new ModelClientValidationRegexRule(message, RegexValidator.Expression));
        }
Esempio n. 4
0
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("From", RangeValidator.From)
                            .AppendArgument("To", RangeValidator.To);
            var messageNeedsSplitting = RangeValidator.ErrorMessageSource.ResourceType == typeof(Messages);

            string message;

            try {
                message = RangeValidator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = Messages.inclusivebetween_error;
                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 {From} and {To}. You entered {Value}.
                // We can't include the "Value" 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 IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
			if(!ShouldGenerateClientSideRules()) yield break;

			// Don't generate clientside rules if min/max are lazily loaded. 
			var lengthVal = LengthValidator as LengthValidator;

			if (lengthVal != null && lengthVal.MaxFunc != null && lengthVal.MinFunc != null) {
				yield break;
			}

			var formatter = new MessageFormatter()
				.AppendPropertyName(Rule.GetDisplayName())
				.AppendArgument("MinLength", LengthValidator.Min)
				.AppendArgument("MaxLength", LengthValidator.Max);

			string message = LengthValidator.ErrorMessageSource.GetString();

			if(LengthValidator.ErrorMessageSource.ResourceType == typeof(Messages)) {
				// 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);

			yield return new ModelClientValidationStringLengthRule(message, LengthValidator.Min, LengthValidator.Max) ;
		}
        public override IEnumerable <ValidationFailure> Validate(PropertyValidatorContext context)
        {
            var results = _innerValidator.Validate(context);

            if (results.Any())
            {
                if (string.IsNullOrWhiteSpace(_message))
                {
                    _onFailureSimple((T)context.Instance, context);
                }
                else
                {
                    var messageFormatter = new MessageFormatter();
                    messageFormatter.AppendPropertyName(context.PropertyName);
                    messageFormatter.AppendArgument("PropertyValue", context.PropertyValue);
                    try
                    {
                        messageFormatter.AppendAdditionalArguments(
                            _funcs.Select(func => func((T)context.Instance, (TProperty)context.PropertyValue)).ToArray());
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }

                    var msg = messageFormatter.BuildMessage(_message);
                    _onFailureComplex((T)context.Instance, context, msg);
                }
            }

            return(results);
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            if (string.IsNullOrEmpty(RegexValidator.Expression))
            {
                yield break;
            }

            var    formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            string message;

            try {
                message = RegexValidator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                // Use provided a message that contains placeholders based on object properties. We can't use that here, so just fall back to the default.
                message = ValidatorOptions.LanguageManager.GetStringForValidator <RegularExpressionValidator>();
            }
            message = formatter.BuildMessage(message);

            yield return(new ModelClientValidationRegexRule(message, RegexValidator.Expression));
        }
Esempio n. 8
0
        public static string GetMessage(RequestData requestData, PropertyValidatorResult propertyValidator)
        {
            MessageFormatter formatter = new MessageFormatter().AppendPropertyName(propertyValidator.DisplayName);
            string           message   = formatter.BuildMessage(propertyValidator.PropertyValidator.Options.ErrorMessageSource.GetString(null));

            return(message);
        }
Esempio n. 9
0
        public void AddEqualToDataAttr(IEnumerable <PropertyValidatorResult> propertyValidators, HtmlTag htmlTag, RequestData request)
        {
            var result = propertyValidators.FirstOrDefault(x => x.PropertyValidator is EqualValidator);

            if (result != null)
            {
                var equal = result.PropertyValidator as EqualValidator;

                if (equal.MemberToCompare != null)
                {
                    MessageFormatter formatter = new MessageFormatter()
                                                 .AppendPropertyName(result.DisplayName)
                                                 .AppendArgument("ComparisonValue", equal.MemberToCompare.Name);

                    string message = formatter.BuildMessage(equal.Options.ErrorMessageSource.GetString(null));

                    htmlTag.Data("val", true);
                    htmlTag.Data("val-equalto", message);
                    if (request.Accessor.PropertyNames.Length > 1)
                    {
                        htmlTag.Data("val-equalto-other", request.Id.Replace("_" + request.Accessor.Name, "") + "_" + equal.MemberToCompare.Name);
                    }
                    else
                    {
                        htmlTag.Data("val-equalto-other", "*." + equal.MemberToCompare.Name);
                    }
                }
            }
        }
        protected override void AddClientValidation(ClientModelValidationContext context)
        {
            string min = Convert.ToString(LengthValidator.Min, CultureInfo.InvariantCulture);
            string max = Convert.ToString(LengthValidator.Max, CultureInfo.InvariantCulture);

            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", min)
                            .AppendArgument("MaxLength", max);

            string message = LengthValidator.ErrorMessageSource.GetString();

            if (LengthValidator.ErrorMessageSource.ResourceType == typeof(Messages))
            {
                // 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);

            MergeClientAttribute(context, "data-val", "true");
            MergeClientAttribute(context, "data-val-length", message);
            if (!string.IsNullOrWhiteSpace(min))
            {
                MergeClientAttribute(context, "data-val-length-min", min);
            }
            if (!string.IsNullOrWhiteSpace(max))
            {
                MergeClientAttribute(context, "data-val-length-max", max);
            }
        }
		public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
			if (!ShouldGenerateClientSideRules()) yield break;

			var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
			var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());
			yield return new ModelClientValidationRequiredRule(message);
		}
Esempio n. 12
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var propertyToCompare = EqualAfterValidator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(Rule.GetDisplayName())
                                .AppendArgument("ComparisonValue", comparisonDisplayName);


                string message = formatter.BuildMessage(EqualAfterValidator.ErrorMessageSource.GetString());
                var    rule    = new ModelClientValidationRule
                {
                    ErrorMessage   = message,       // default error message
                    ValidationType = "equaltoafter" // name of the validatoin which will be used inside unobtrusive library
                };
                rule.ValidationParameters["other"] = CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name);
                yield return(rule);
            }
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var propertyToCompare = CheckBoxCheckValidator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(Rule.GetDisplayName())
                                .AppendArgument("PropertyNameTo", comparisonDisplayName);

                string message = formatter.BuildMessage(CheckBoxCheckValidator.ErrorMessageSource.GetString());

                var rule = new ModelClientValidationRule
                {
                    ErrorMessage   = message,
                    ValidationType = "checkboxcheck"
                };

                rule.ValidationParameters["comparewith"] = propertyToCompare.Name;
                yield return(rule);
            }
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var paramName = string.Empty;

            if (NotFileExeBatValidator.MemberParams != null)
            {
                foreach (var item in NotFileExeBatValidator.MemberParams)
                {
                    paramName += item.Name + ",";
                }
            }
            paramName = paramName.TrimEnd(',');
            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName());

            string message = formatter.BuildMessage(NotFileExeBatValidator.ErrorMessageSource.GetString());

            var rule = new ModelClientValidationRule
            {
                ErrorMessage   = message,        // default error message
                ValidationType = "notfileexebat" // name of the validatoin which will be used inside unobtrusive library
            };

            //rule.ValidationParameters["keyid"] = StoreValidator.KeyId;
            rule.ValidationParameters["parameternames"] = paramName; // html element which includes prefix information
            yield return(rule);
        }
Esempio n. 15
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var propertyToCompare = this.Validator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(this.Validator.MemberToCompare.DeclaringType, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(context.ModelMetadata.PropertyName)
                                .AppendArgument("ComparisonValue", comparisonDisplayName);


                string message = formatter.BuildMessage(this.Validator.Options.ErrorMessageSource.GetString(null));
                context.Attributes.AddIfNotExisting("data-val", "true");
                context.Attributes.AddIfNotExisting("data-val-equalto", message);
                context.Attributes.AddIfNotExisting("data-val-equalto-other", $"*.{propertyToCompare.Name}");
            }
        }
Esempio n. 16
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(Rule.GetDisplayName())
                                .AppendArgument("ComparisonValue", comparisonDisplayName);

                string messageTemplate;
                try {
                    messageTemplate = EqualValidator.ErrorMessageSource.GetString(null);
                }
                catch (FluentValidationMessageFormatException) {
                    messageTemplate = ValidatorOptions.LanguageManager.GetStringForValidator <EqualValidator>();
                }
                string message = formatter.BuildMessage(messageTemplate);
                MergeAttribute(context.Attributes, "data-val", "true");
                MergeAttribute(context.Attributes, "data-val-equalto", message);
                MergeAttribute(context.Attributes, "data-val-equalto-other", propertyToCompare.Name);
            }
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", LengthValidator.Min)
                            .AppendArgument("MaxLength", LengthValidator.Max);

            string message = LengthValidator.ErrorMessageSource.GetString(Metadata);

            if (LengthValidator.ErrorMessageSource.ResourceType == typeof(Messages))
            {
                // 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);

            yield return(new ModelClientValidationStringLengthRule(message, LengthValidator.Min, LengthValidator.Max));
        }
Esempio n. 18
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)
            {
                message = ValidatorOptions.LanguageManager.GetStringForValidator <MaximumLengthValidator>();
                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 IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;

            if (propertyToCompare != null)
            {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var comparisonDisplayName =
                    ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
                    ?? propertyToCompare.Name.SplitPascalCase();

                var formatter = new MessageFormatter()
                                .AppendPropertyName(Rule.GetDisplayName())
                                .AppendArgument("ComparisonValue", comparisonDisplayName);


                string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString());
                yield return(new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)));
            }
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            string comparisonValuePlaceHolder = "ComparisonValue";

            // Convert validator
            NotEqualValidator notEqualValidator = (NotEqualValidator)Validator;

            // Initialize client rule
            ModelClientValidationRule rule = new ModelClientValidationRule();

            rule.ValidationType = "notequal";

            MessageFormatter formatter = new MessageFormatter()
                                         .AppendPropertyName(Metadata.DisplayName ?? Rule.PropertyName);

            if (notEqualValidator.MemberToCompare != null)
            {
                // Append comparision member to message
                formatter.AppendArgument(
                    comparisonValuePlaceHolder,
                    notEqualValidator.MemberToCompare.GetDisplayName());

                // Append '*.' to the name of field for prefix merging
                rule.ValidationParameters["field"] = string.Format("*.{0}",
                                                                   notEqualValidator.MemberToCompare.Name);
            }
            else if (notEqualValidator.ValueToCompare != null)
            {
                string valueToCompare = null;

                if (notEqualValidator.ValueToCompare is DateTime)
                {
                    // If value is of type DateTime convert it to DateTime
                    // and format as yyyy-MM-dd to be able to parse it at client side
                    // easily using jQuery.
                    DateTime dateValueToCompare = (DateTime)notEqualValidator.ValueToCompare;
                    valueToCompare = dateValueToCompare.ToString("yyyy-MM-dd");
                }
                else
                {
                    valueToCompare = notEqualValidator.ValueToCompare.ToString();
                }

                // Append comparision value to message
                formatter.AppendArgument(comparisonValuePlaceHolder, valueToCompare);
                // Set value to compare
                rule.ValidationParameters["value"] = valueToCompare;
            }

            // Set error message of rule
            rule.ErrorMessage = formatter.BuildMessage(Validator.ErrorMessageSource.GetString(null));

            yield return(rule);
        }
Esempio n. 21
0
        /// <summary>
        /// Adds client validation
        /// </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());

            MergeClientAttribute(context, "data-val", "true");
            MergeClientAttribute(context, "data-val-required", message);
        }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules()) yield break;

            var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
            string message = formatter.BuildMessage(RegexValidator.ErrorMessageSource.GetString());
            yield return new ModelClientValidationRegexRule(message, RegexValidator.Expression);
        }
Esempio n. 23
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var formatter = new MessageFormatter().AppendPropertyName(context.ModelMetadata.PropertyName);
            var message   = formatter.BuildMessage(Validator.Options.ErrorMessageSource.GetString(null));

            context.Attributes.AddIfNotExisting("data-val", "true");
            context.Attributes.AddIfNotExisting("data-val-required", message);
        }
Esempio n. 24
0
		public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
			var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
			string message = formatter.BuildMessage(EmailValidator.ErrorMessageSource.GetString());
			
			yield return new ModelClientValidationRule {
			                                           	ValidationType = "email",
			                                           	ErrorMessage = message
			                                           };
		}
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
            string message = formatter.BuildMessage(EmailValidator.ErrorMessageSource.GetString());

            yield return new ModelClientValidationRule {
                                                       	ValidationType = "email",
                                                       	ErrorMessage = message
                                                       };
        }
Esempio n. 26
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }
            var    formatter = new MessageFormatter().AppendPropertyName(base.Rule.DisplayName.ResourceName);
            string message   = formatter.BuildMessage(RemoteValidator.ErrorMessageSource.GetString());

            yield return(new ModelClientValidationRemoteRule(message, RemoteValidator.Url, RemoteValidator.HttpMethod, RemoteValidator.AdditionalFields));
        }
		public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
			if (!ShouldGenerateClientSideRules()) yield break;

			var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
			string message = formatter.BuildMessage(EmailValidator.ErrorMessageSource.GetString());
			
			yield return new ModelClientValidationRule {
			                                           	ValidationType = "email",
			                                           	ErrorMessage = message
			                                           };
		}
Esempio n. 28
0
        public string GetFormattedErrorMessage(Type type, MessageFormatter formatter)
        {
            string error = CustomError ?? ValidationMessageAttribute.GetMessage(type);

            if (customFormatArgs != null)
            {
                formatter.AppendAdditionalArguments(
                    customFormatArgs.Select(func => func(Instance)).ToArray()
                    );
            }
            return(formatter.BuildMessage(error));
        }
Esempio n. 29
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            var message   = formatter.BuildMessage(Validator.ErrorMessageSource.GetString(Metadata));

            yield return(new ModelClientValidationRequiredRule(message));
        }
        public string ConstructMessage(string message, string propertyName, params string[] additionalPropertyNames)
        {
            if (additionalPropertyNames == null)
            {
                throw new ArgumentNullException("additionalPropertyNames");
            }
            var messageFormatter = new MessageFormatter();

            messageFormatter.AppendPropertyName(propertyName);
            messageFormatter.AppendAdditionalArguments(additionalPropertyNames);
            return(messageFormatter.BuildMessage(message));
        }
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var    formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
            string message   = formatter.BuildMessage(RemoteValidator.ErrorMessageSource.GetString(null));

            //This is the rule that asp.net mvc 3, uses for Remote attribute.
            yield return(new ModelClientValidationRemoteRule(message, RemoteValidator.Url, RemoteValidator.HttpMethod, RemoteValidator.AdditionalFields));
        }
        /// <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 minValue  = Convert.ToString(MaxValue, CultureInfo.InvariantCulture);

            if (!string.IsNullOrWhiteSpace(minValue))
            {
                MergeClientAttribute(context, "data-val", "true");
                MergeClientAttribute(context, "data-val-range", message);
                MergeClientAttribute(context, "data-val-range-max", minValue);
            }
        }
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var messageFormatter = new MessageFormatter().AppendPropertyName(metadata.DisplayName);
            var FormattedMessage = messageFormatter.BuildMessage(Options.ErrorMessageSource.GetString(null));

            var rule = new ModelClientValidationRule
            {
                ErrorMessage   = FormattedMessage,
                ValidationType = "requiredcheckbox"
            };

            yield return(rule);
        }
Esempio n. 34
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

            var formatter = new MessageFormatter()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("ComparisonValue", AbstractComparisonValidator.ValueToCompare);
            var message = formatter.BuildMessage(AbstractComparisonValidator.ErrorMessageSource.GetString());

            yield return(new ModelClientValidationRangeRule(message, MinValue, MaxValue));
        }
Esempio n. 35
0
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    formatter = new MessageFormatter().AppendPropertyName(Rule.GetDisplayName());
            string message;

            try {
                message = Validator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = Messages.CreditCardError;
            }
            message = formatter.BuildMessage(message);
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "creditcard", message);
        }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;
            if(propertyToCompare != null) {
                // If propertyToCompare is not null then we're comparing to another property.
                // If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
                // We only care about property comparisons in this case.

                var formatter = new MessageFormatter()
                    .AppendPropertyName(Rule.PropertyDescription)
                    .AppendArgument("PropertyValue", propertyToCompare.Name);

                string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString());
                yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ;
            }
        }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var formatter = new MessageFormatter()
                .AppendPropertyName(Rule.PropertyDescription)
                .AppendArgument("From", RangeValidator.From)
                .AppendArgument("To", RangeValidator.To);

            string message = RangeValidator.ErrorMessageSource.GetString();

            if (RangeValidator.ErrorMessageSource.ResourceType == typeof(Messages)) {
                // If we're using the default resources then the mesage for length errors will have two parts, eg:
                // '{PropertyName}' must be between {From} and {To}. You entered {Value}.
                // We can't include the "Value" 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);

            yield return new ModelClientValidationRangeRule(message, RangeValidator.From, RangeValidator.To);
        }
		public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
			if (!ShouldGenerateClientSideRules()) yield break;

			var propertyToCompare = EqualValidator.MemberToCompare as PropertyInfo;
			if(propertyToCompare != null) {
				// If propertyToCompare is not null then we're comparing to another property.
				// If propertyToCompare is null then we're either comparing against a literal value, a field or a method call.
				// We only care about property comparisons in this case.

				var comparisonDisplayName =
					ValidatorOptions.DisplayNameResolver(Rule.TypeToValidate, propertyToCompare, null)
					?? propertyToCompare.Name.SplitPascalCase();

				var formatter = new MessageFormatter()
					.AppendPropertyName(Rule.GetDisplayName())
					.AppendArgument("ComparisonValue", comparisonDisplayName);


				string message = formatter.BuildMessage(EqualValidator.ErrorMessageSource.GetString());
				yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ;
			}
		}
 public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
 {
     var formatter = new MessageFormatter().AppendPropertyName(propertyDescription);
     var message = formatter.BuildMessage(validator.ErrorMessageSource.GetString());
     return new[] { new ModelClientValidationRequiredRule(message) };
 }
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var formatter = new MessageFormatter().AppendPropertyName(propertyDescription);
            string message = LengthValidator.ErrorMessageSource.GetString();

            if(LengthValidator.ErrorMessageSource.ResourceType == typeof(Messages)) {
                // 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);

                // also append the min/max bits
                formatter.AppendArgument("MinLength", LengthValidator.Min)
                    .AppendArgument("MaxLength", LengthValidator.Max);
            }

            message = formatter.BuildMessage(message);

            return new[] { new ModelClientValidationStringLengthRule(message, LengthValidator.Min, LengthValidator.Max) };
        }