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

            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("From", RangeValidator.From)
                            .AppendArgument("To", RangeValidator.To);

            var needsSimplifiedMessage = RangeValidator.Options.ErrorMessageSource is LanguageStringSource;

            string message;

            try {
                message = RangeValidator.Options.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.GetString("InclusiveBetween_Simple");
                needsSimplifiedMessage = false;
            }

            if (needsSimplifiedMessage && message.Contains("{Value}"))
            {
                message = ValidatorOptions.LanguageManager.GetString("InclusiveBetween_Simple");
            }

            message = formatter.BuildMessage(message);

            yield return(new ModelClientValidationRangeRule(message, RangeValidator.From, RangeValidator.To));
        }
Example #2
0
        /// <summary>
        /// Creates an error validation result for this validator.
        /// </summary>
        /// <param name="context">The validator context</param>
        /// <returns>Returns an error validation result.</returns>
        protected virtual ValidationFailure CreateValidationError(PropertyValidatorContext context)
        {
            var messageBuilderContext = new MessageBuilderContext(context, errorSource, this);

            var error = context.Rule.MessageBuilder != null
                                ? context.Rule.MessageBuilder(messageBuilderContext)
                                : messageBuilderContext.GetDefaultMessage();

            var failure = new ValidationFailure(context.PropertyName, error, context.PropertyValue);

            failure.FormattedMessageArguments         = context.MessageFormatter.AdditionalArguments;
            failure.FormattedMessagePlaceholderValues = context.MessageFormatter.PlaceholderValues;
            failure.ResourceName = errorSource.ResourceName;
            failure.ErrorCode    = (errorCodeSource != null)
                                ? errorCodeSource.GetString(context.Instance)
                                : ValidatorOptions.ErrorCodeResolver(this);

            if (CustomStateProvider != null)
            {
                failure.CustomState = CustomStateProvider(context);
            }

            failure.Severity = Severity;
            return(failure);
        }
        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);
            }
        }
Example #4
0
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("From", RangeValidator.From)
                            .AppendArgument("To", RangeValidator.To);

            var needsSimplifiedMessage = RangeValidator.Options.ErrorMessageSource is LanguageStringSource;

            string message;

            try {
                message = RangeValidator.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetString("InclusiveBetween_Simple");
                needsSimplifiedMessage = false;
            }

            if (needsSimplifiedMessage && message.Contains("{Value}"))
            {
                message = ValidatorOptions.LanguageManager.GetString("InclusiveBetween_Simple");
            }
            message = formatter.BuildMessage(message);

            return(message);
        }
Example #5
0
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("ComparisonValue", RangeValidator.ValueToCompare);

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

            string message;

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

            if (messageNeedsSplitting && message.Contains(".") && message.Contains("{ComparisonValue}"))
            {
                // 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);
        }
Example #6
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);
            }
        }
Example #7
0
        public override IEnumerable <ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules())
            {
                yield break;
            }

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

            var    formatter = ValidatorOptions.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string message;

            try {
                message = Validator.Options.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));
        }
		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 = ValidatorOptions.MessageFormatterFactory()
					.AppendPropertyName(Rule.GetDisplayName())
					.AppendArgument("ComparisonValue", comparisonDisplayName);


				string message;
				try {
					message = EqualValidator.Options.ErrorMessageSource.GetString(null);
					
				}
				catch (FluentValidationMessageFormatException) {
					// User 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<EqualValidator>();
				}
				message = formatter.BuildMessage(message);
#pragma warning disable 618
				yield return new ModelClientValidationEqualToRule(message, CompareAttribute.FormatPropertyForClientValidation(propertyToCompare.Name)) ;
#pragma warning restore 618
			}
		}
Example #9
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);
            }
        }
Example #10
0
        private string GetErrorMessage(LengthValidator lengthVal, ClientModelValidationContext context)
        {
            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", lengthVal.Min)
                            .AppendArgument("MaxLength", lengthVal.Max);

            bool messageNeedsSplitting = lengthVal.Options.ErrorMessageSource.ResourceType == typeof(LanguageManager);

            string message;

            try {
                message = lengthVal.Options.ErrorMessageSource.GetString(null);
            } catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetStringForValidator <MaximumLengthValidator>();
                messageNeedsSplitting = true;
            }

            if (messageNeedsSplitting && message.Contains(".") && message.Contains("{TotalLength}"))
            {
                // 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)
        {
            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 = ValidatorOptions.MessageFormatterFactory()
                                .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);
            }
        }
        private string GetErrorMessage(LengthValidator lengthVal, ClientModelValidationContext context)
        {
            var formatter = ValidatorOptions.MessageFormatterFactory()
                            .AppendPropertyName(Rule.GetDisplayName())
                            .AppendArgument("MinLength", lengthVal.Min)
                            .AppendArgument("MaxLength", lengthVal.Max);

            bool needsSimifiedMessage = lengthVal.Options.ErrorMessageSource is LanguageStringSource;

            string message;

            try {
                message = lengthVal.Options.ErrorMessageSource.GetString(null);
            } catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetString("MinimumLength_Simple");
                needsSimifiedMessage = false;
            }

            if (needsSimifiedMessage && message.Contains("{TotalLength}"))
            {
                message = ValidatorOptions.LanguageManager.GetString("MinimumLength_Simple");
            }

            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)));
            }
        }
        /// <summary>
        /// Gets all the assigned validators for the given Editor.
        /// </summary>
        /// <param name="editor"></param>
        /// <returns>ValidatorCollection</returns>
        private ValidatorCollection GetEditorValidators(FieldSuiteEditor editor)
        {
            ValidatorCollection validators = ValidatorManager.BuildValidators(ValidatorsMode.ValidatorBar, editor.Item);
            ValidatorOptions    options    = new ValidatorOptions(false);

            foreach (string marker in editor.FieldInfo.Keys)
            {
                FieldInfo fieldInfo = editor.FieldInfo[marker] as FieldInfo;
                if (fieldInfo == null)
                {
                    continue;
                }
                Sitecore.Data.Validators.BaseValidator validator = validators.Where(x => x.FieldID == fieldInfo.FieldID).FirstOrDefault();
                if (validator == null)
                {
                    continue;
                }
                validator.ControlToValidate = marker;
            }

            ValidatorManager.Validate(validators, options);
            ValidatorManager.UpdateValidators(validators);

            return(validators);
        }
Example #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}");
            }
        }
Example #16
0
        private static bool IsItemValid(this Item item)
        {
            if (((item != null) && !item.Paths.IsMasterPart) && !StandardValuesManager.IsStandardValuesHolder(item))
            {
                item.Fields.ReadAll();
                item.Fields.Sort();
                foreach (Field field in item.Fields)
                {
                    if (!string.IsNullOrEmpty(field.Validation) && !Regex.IsMatch(field.Value, field.Validation, RegexOptions.Singleline))
                    {
                        return(false);
                    }
                }


                var formValue = WebUtil.GetFormValue("scValidatorsKey");
                if (!string.IsNullOrEmpty(formValue))
                {
                    var validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
                    var options    = new ValidatorOptions(true);
                    ValidatorManager.Validate(validators, options);
                    var valid = ValidatorResult.Valid;
                    foreach (BaseValidator validator in validators)
                    {
                        var result = validator.Result;
                        if (validator.ItemUri != null)
                        {
                            var item1 = Client.ContentDatabase.GetItem(validator.ItemUri.ToDataUri());
                            if (((item1 != null) && StandardValuesManager.IsStandardValuesHolder(item1)) && (result > ValidatorResult.CriticalError))
                            {
                                result = ValidatorResult.CriticalError;
                            }
                        }

                        if (result > valid)
                        {
                            valid = validator.Result;
                        }

                        if (validator.IsEvaluating && (validator.MaxValidatorResult >= ValidatorResult.CriticalError))
                        {
                            return(false);
                        }
                    }

                    switch (valid)
                    {
                    case ValidatorResult.CriticalError:
                        return(false);

                    case ValidatorResult.FatalError:

                        return(false);
                    }
                }
            }

            return(true);
        }
Example #17
0
        public void ResolvePropertyName_ChildProperty_ReturnsExpectedPropertyName()
        {
            Expression <Func <PatchDTO, string> > memberAccessor = patchDto => patchDto.Data[0].Id;
            var resolvedPropertyName = ValidatorOptions.PropertyNameResolver(typeof(PatchDTO), memberAccessor.GetMember(), memberAccessor);

            Assert.That(resolvedPropertyName, Is.EqualTo("Id"));
            //Assert.That(resolvedPropertyName, Is.EqualTo("Data[0].Id"));
        }
        private static bool IsItemValid(this Item item)
        {
            if (((item != null) && !item.Paths.IsMasterPart) && !StandardValuesManager.IsStandardValuesHolder(item))
            {
                item.Fields.ReadAll();
                item.Fields.Sort();
                foreach (Field field in item.Fields)
                {
                    if (!string.IsNullOrEmpty(field.Validation) && !Regex.IsMatch(field.Value, field.Validation, RegexOptions.Singleline))
                    {
                        return false;
                    }
                }

                var formValue = WebUtil.GetFormValue("scValidatorsKey");
                if (!string.IsNullOrEmpty(formValue))
                {
                    var validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
                    var options = new ValidatorOptions(true);
                    ValidatorManager.Validate(validators, options);
                    var valid = ValidatorResult.Valid;
                    foreach (BaseValidator validator in validators)
                    {
                        var result = validator.Result;
                        if (validator.ItemUri != null)
                        {
                            var item1 = Client.ContentDatabase.GetItem(validator.ItemUri.ToDataUri());
                            if (((item1 != null) && StandardValuesManager.IsStandardValuesHolder(item1)) && (result > ValidatorResult.CriticalError))
                            {
                                result = ValidatorResult.CriticalError;
                            }
                        }

                        if (result > valid)
                        {
                            valid = validator.Result;
                        }

                        if (validator.IsEvaluating && (validator.MaxValidatorResult >= ValidatorResult.CriticalError))
                        {
                            return false;
                        }
                    }

                    switch (valid)
                    {
                        case ValidatorResult.CriticalError:
                            return false;

                        case ValidatorResult.FatalError:

                            return false;
                    }
                }
            }

            return true;
        }
        /// <summary>
        /// Creates a new property rule.
        /// </summary>
        /// <param name="member">Property</param>
        /// <param name="propertyFunc">Function to get the property value</param>
        /// <param name="expression">Lambda expression used to create the rule</param>
        /// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
        /// <param name="typeToValidate">Type to validate</param>
        /// <param name="containerType">Container type that owns the property</param>
        public PropertyRule(MemberInfo member, PropertySelector propertyFunc, Expression expression, Func <CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType)
        {
            Member                = member;
            PropertyFunc          = propertyFunc;
            Expression            = expression;
            OnFailure             = x => { };
            TypeToValidate        = typeToValidate;
            this.cascadeModeThunk = cascadeModeThunk;

            PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member);
        }
Example #20
0
        /// <summary>
        /// Creates a new property rule.
        /// </summary>
        /// <param name="member">Property</param>
        /// <param name="propertyFunc">Function to get the property value</param>
        /// <param name="expression">Lambda expression used to create the rule</param>
        /// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
        /// <param name="typeToValidate">Type to validate</param>
        /// <param name="containerType">Container type that owns the property</param>
        public PropertyRule(MemberInfo member, Func <object, object> propertyFunc, LambdaExpression expression, Func <CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType)
        {
            Member                = member;
            PropertyFunc          = propertyFunc;
            Expression            = expression;
            OnFailure             = x => { };
            TypeToValidate        = typeToValidate;
            this.cascadeModeThunk = cascadeModeThunk;

            PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
            DisplayName  = new LazyStringSource(() => ValidatorOptions.DisplayNameResolver(containerType, member, expression));
        }
Example #21
0
        /// <summary>
        /// Creates a new property rule.
        /// </summary>
        /// <param name="member">Property</param>
        /// <param name="propertyFunc">Function to get the property value</param>
        /// <param name="expression">Lambda expression used to create the rule</param>
        /// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
        /// <param name="typeToValidate">Type to validate</param>
        /// <param name="containerType">Container type that owns the property</param>
        public PropertyRule(MemberInfo member, Func <object, object> propertyFunc, LambdaExpression expression, Func <CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType, Func <PropertyRule, string> _LoadDisplayName)
        {
            Member       = member;
            PropertyFunc = propertyFunc;
            //	Expression = expression;
            OnFailure             = x => { };
            TypeToValidate        = typeToValidate;
            this.cascadeModeThunk = cascadeModeThunk;

            DependentRules  = new List <IValidationRule>();
            PropertyName    = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
            LoadDisplayName = _LoadDisplayName;
        }
        public static ValidatorCollection GetValidationResult(this Item item, ValidatorsMode validationMode = ValidatorsMode.ValidatorBar)
        {
            var validators = ValidatorManager.BuildValidators(validationMode, item);

            if (validators.Count == 0)
            {
                return(new ValidatorCollection());
            }

            ValidatorOptions options = new ValidatorOptions(true);

            ValidatorManager.Validate(validators, options);

            return(validators);
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    formatter = ValidatorOptions.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string message;

            try {
                message = Validator.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                message = ValidatorOptions.LanguageManager.GetStringForValidator <CreditCardValidator>();
            }
            message = formatter.BuildMessage(message);
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-creditcard", message);
        }
Example #24
0
        private string GetErrorMessage(ClientModelValidationContext context)
        {
            var    formatter = ValidatorOptions.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string messageTemplate;

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

            return(message);
        }
Example #25
0
        private string GetPropertyName(IEnumerable <MemberInfo> properties)
        {
            var propertiesList = properties.Where(x => x != null).Select(x => x.Name).ToList();

            if (MemberAccessor != null)
            {
                string memberName = ValidatorOptions.PropertyNameResolver(typeof(T), MemberAccessor.Member, MemberAccessor);

                if (!string.IsNullOrEmpty(memberName))
                {
                    propertiesList.Insert(0, memberName);
                }
            }

            return(string.Join(".", propertiesList));
        }
Example #26
0
        /// <summary>
        /// Creates an error validation result for this validator.
        /// </summary>
        /// <param name="context">The validator context</param>
        /// <returns>Returns an error validation result.</returns>
        protected virtual ValidationFailure CreateValidationError(PropertyValidatorContext context)
        {
            var messageBuilderContext = new MessageBuilderContext(context, Options.ErrorMessageSource, this);

            var error = context.Rule.MessageBuilder != null
                ? context.Rule.MessageBuilder(messageBuilderContext)
                : messageBuilderContext.GetDefaultMessage();

            var failure = new ValidationFailure(context.PropertyName, error, context.PropertyValue);

            //failure.FormattedMessageArguments = context.MessageFormatter.AdditionalArguments;
            failure.FormattedMessagePlaceholderValues = context.MessageFormatter.PlaceholderValues;
            failure.ErrorCode = (Options.ErrorCodeSource != null)
                ? Options.ErrorCodeSource.GetString(context)
                : ValidatorOptions.ErrorCodeResolver(this);
            return(failure);
        }
Example #27
0
        /// <summary>
        /// Creates a new property rule.
        /// </summary>
        /// <param name="member">Property</param>
        /// <param name="propertyFunc">Function to get the property value</param>
        /// <param name="expression">Lambda expression used to create the rule</param>
        /// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
        /// <param name="typeToValidate">Type to validate</param>
        /// <param name="containerType">Container type that owns the property</param>
        public PropertyRule(MemberInfo member, Func <object, object> propertyFunc, LambdaExpression expression, Func <CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType)
        {
            Member                = member;
            PropertyFunc          = propertyFunc;
            Expression            = expression;
            OnFailure             = x => { };
            TypeToValidate        = typeToValidate;
            this.cascadeModeThunk = cascadeModeThunk;

            PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
            string displayName = ValidatorOptions.DisplayNameResolver(containerType, member, expression);

            if (!string.IsNullOrEmpty(displayName))
            {
                DisplayName = new StaticStringSource(displayName);
            }
        }
        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 <GreaterThanOrEqualValidator>();
            }

            message = formatter.BuildMessage(message);

            return(message);
        }
        public override void AddValidation(ClientModelValidationContext context)
        {
            var    regexVal  = (RegularExpressionValidator)Validator;
            var    formatter = ValidatorOptions.MessageFormatterFactory().AppendPropertyName(Rule.GetDisplayName());
            string messageTemplate;

            try {
                messageTemplate = regexVal.Options.ErrorMessageSource.GetString(null);
            }
            catch (FluentValidationMessageFormatException) {
                messageTemplate = ValidatorOptions.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);
        }
        private IEnumerable <string> GetMemberNames()
        {
            if (_testValidationResult.MemberAccessor == null)
            {
                yield break;
            }

            string memberName = ValidatorOptions.PropertyNameResolver(
                typeof(T),
                _testValidationResult.MemberAccessor.Member,
                _testValidationResult.MemberAccessor
                );

            if (!string.IsNullOrEmpty(memberName))
            {
                yield return(memberName);
            }
        }
Example #31
0
        private string WriteValidators([NotNull] Item targetItem)
        {
            Debug.ArgumentNotNull(targetItem, nameof(targetItem));

            var writer = new StringWriter();
            var output = new XmlTextWriter(writer);

            output.WriteStartElement("validators");

            var validatorCollection = ValidatorManager.BuildValidators(ValidatorsMode.ValidatorBar, targetItem);

            var options = new ValidatorOptions(true);

            ValidatorManager.Validate(validatorCollection, options);

            foreach (BaseValidator validator in validatorCollection)
            {
                if (validator.Result == ValidatorResult.Valid || validator.Result == ValidatorResult.Unknown)
                {
                    continue;
                }

                var fieldId          = string.Empty;
                var validatorFieldId = validator.FieldID;
                if ((object)validatorFieldId != null && !validatorFieldId.IsNull)
                {
                    fieldId = validatorFieldId.ToString();
                }

                output.WriteStartElement("validator");

                output.WriteAttributeString("fieldid", fieldId);
                output.WriteAttributeString("validatorid", validator.ValidatorID.ToString());
                output.WriteAttributeString("result", ((int)validator.Result).ToString());
                output.WriteValue(validator.Text);

                output.WriteEndElement();
            }

            output.WriteEndElement();

            return(writer.ToString());
        }
 protected string UpdateValidators(Item folder)
 {
     Assert.ArgumentNotNull(folder, "folder");
     Assert.IsTrue(UserOptions.ContentEditor.ShowValidatorBar, "Validator bar is switched off in Content Editor.");
     ValidatorCollection validators = this.BuildValidators(ValidatorsMode.ValidatorBar, folder);
     ValidatorOptions options = new ValidatorOptions(false);
     ValidatorManager.Validate(validators, options);
     return ValidatorBarFormatter.RenderValidationResult(validators);
 }
Example #33
0
    private bool RunValidation(ValidatorsMode mode, StringBuilder output, ref int count)
    {
      var validators = ValidatorManager.BuildValidators(mode, Context.CurrentItem);
      count += validators.Count;

      var options = new ValidatorOptions(true);
      ValidatorManager.Validate(validators, options);

      var success = true;

      foreach(BaseValidator val in validators)
      {
        if (Verbose || val.Result != ValidatorResult.Valid)
          Formatter.PrintDefinition(val.Name, val.Result.ToString(), 60, output);

        if (val.Result != ValidatorResult.Valid)
          success = false;
      }

      return success;
    }
        /// <summary>
        /// Gets all the assigned validators for the given Editor.
        /// </summary>
        /// <param name="editor"></param>
        /// <returns>ValidatorCollection</returns>
        private ValidatorCollection GetEditorValidators(FieldSuiteEditor editor)
        {
            ValidatorCollection validators = ValidatorManager.BuildValidators(ValidatorsMode.ValidatorBar, editor.Item);
            ValidatorOptions options = new ValidatorOptions(false);

            foreach (string marker in editor.FieldInfo.Keys)
            {
                FieldInfo fieldInfo = editor.FieldInfo[marker] as FieldInfo;
                if (fieldInfo == null) continue;
                Sitecore.Data.Validators.BaseValidator validator = validators.Where(x => x.FieldID == fieldInfo.FieldID).FirstOrDefault();
                if (validator == null) continue;
                validator.ControlToValidate = marker;
            }

            ValidatorManager.Validate(validators, options);
            ValidatorManager.UpdateValidators(validators);

            return validators;
        }
 protected void ShowValidationResult(Item folder)
 {
     Assert.ArgumentNotNull(folder, "folder");
     ValidatorCollection validators = this.BuildValidators(ValidatorsMode.ValidateButton, folder);
     ValidatorOptions options = new ValidatorOptions(true);
     ValidatorManager.Validate(validators, options);
     IFormatter formatter = new BinaryFormatter();
     MemoryStream serializationStream = new MemoryStream();
     formatter.Serialize(serializationStream, validators);
     serializationStream.Close();
     UrlHandle handle = new UrlHandle();
     handle["validators"] = Convert.ObjectToBase64(serializationStream.ToArray());
     UrlString urlString = new UrlString("/sitecore/shell/~/xaml/Sitecore.Shell.Applications.ContentEditor.Dialogs.ValidationResult.aspx");
     handle.Add(urlString);
     SheerResponse.ShowModalDialog(urlString.ToString());
 }
 protected void ValidateItem()
 {
     Assert.IsTrue(UserOptions.ContentEditor.ShowValidatorBar, "Validator bar is switched off in Content Editor.");
     string formValue = WebUtil.GetFormValue("scValidatorsKey");
     ValidatorCollection validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
     ValidatorOptions options = new ValidatorOptions(false);
     ValidatorManager.Validate(validators, options);
     string text = ValidatorBarFormatter.RenderValidationResult(validators);
     SheerResponse.Eval(string.Format("scContent.renderValidators({0},{1})", StringUtil.EscapeJavascriptString(text), Settings.Validators.UpdateFrequency));
 }
 private void UpdateValidatorBar(Item folder, Border parent)
 {
     Assert.ArgumentNotNull(folder, "folder");
     Assert.ArgumentNotNull(parent, "parent");
     if (UserOptions.ContentEditor.ShowValidatorBar)
     {
         ValidatorCollection validators = this.BuildValidators(ValidatorsMode.ValidatorBar, folder);
         ValidatorOptions options = new ValidatorOptions(false);
         ValidatorManager.Validate(validators, options);
         string str = ValidatorBarFormatter.RenderValidationResult(validators);
         bool flag = str.IndexOf("Applications/16x16/bullet_square_grey.png") >= 0;
         if (Context.ClientPage.IsEvent)
         {
             SheerResponse.Eval("scContent.clearValidatorTimeouts()");
             SheerResponse.SetInnerHtml("ValidatorPanel", str);
             SheerResponse.SetAttribute("scHasValidators", "value", (validators.Count > 0) ? "1" : string.Empty);
             SheerResponse.Eval("scContent.updateFieldMarkers()");
             if (flag)
             {
                 SheerResponse.Eval("window.setTimeout(\"scContent.updateValidators()\", " + Settings.Validators.UpdateFrequency + ")");
             }
             SheerResponse.Redraw();
         }
         else
         {
             var control = parent.FindControl("ValidatorPanel");
             if (control != null)
             {
                 control.Controls.Add(new LiteralControl(str));
                 Context.ClientPage.FindControl("ContentEditorForm").Controls.Add(new LiteralControl("<input type=\"hidden\" id=\"scHasValidators\" name=\"scHasValidators\" value=\"" + ((validators.Count > 0) ? "1" : string.Empty) + "\"/>"));
                 if (flag)
                 {
                     control.Controls.Add(new LiteralControl("<script type=\"text/javascript\" language=\"javascript\">window.setTimeout('scContent.updateValidators()', " + Settings.Validators.UpdateFrequency + ")</script>"));
                 }
                 control.Controls.Add(new LiteralControl("<script type=\"text/javascript\" language=\"javascript\">scContent.updateFieldMarkers()</script>"));
             }
         }
     }
 }