Ejemplo n.º 1
0
 public PropertyType(int key, IPropertyValidator propertyValidator, GroupTypeCollection groupsRead, GroupTypeCollection groupsWrite)
 {
     Key = key;
     Validator = propertyValidator;
     GroupsReadInternal = groupsRead;
     GroupsWriteInternal = groupsWrite;
 }
Ejemplo n.º 2
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     return new Required
     {
         Message = propertyValidator.GetErrorMessageFor(propertyName)
     };
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return new RegexValidationRule(
         FormatMessage(rule, validator),
         GetMemberNames(rule),
         ((IRegularExpressionValidator)validator).Expression);
 }
Ejemplo n.º 4
0
 public Rule GeneratorFrom(IPropertyValidator propertyValidator)
 {
     return new Required
     {
         Message = propertyValidator.ErrorMessageSource.GetString()
     };
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a <see cref="IFluentAdapter"/> instance based on the provided <paramref name="propertyValidator"/>.
        /// </summary>
        /// <param name="propertyValidator">The <see cref="IPropertyValidator"/> for which the adapter should be created.</param>
        /// <returns>An <see cref="IFluentAdapter"/> instance.</returns>
        public IFluentAdapter Create(IPropertyValidator propertyValidator)
        {
            var adapter =
                this.adapters.SingleOrDefault(x => x.CanHandle(propertyValidator));

            return adapter ?? new FallbackAdapter();
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return new ModelValidationRule(
         "Custom",
         base.FormatMessage(rule, validator),
         base.GetMemberNames(rule));
 }
        public DataAnnotationsValidatorFixture()
        {
            this.propertyValidator1 =
                A.Fake<IPropertyValidator>();

            this.propertyValidator2 =
                A.Fake<IPropertyValidator>();

            this.validatableObjectAdapter =
                A.Fake<IValidatableObjectAdapter>();

            this.validatorFactory =
                A.Fake<IPropertyValidatorFactory>();

            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))
               .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });

            this.validator =
                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);

            var adapterFactory = new DefaultPropertyValidatorFactory(new IDataAnnotationsValidatorAdapter[]
            {
                new RangeValidatorAdapter(),
                new RegexValidatorAdapter(),
                new RequiredValidatorAdapter(),
                new StringLengthValidatorAdapter(),
                new OopsAdapter()
            });

            var adapter = A.Fake<IValidatableObjectAdapter>();

            this.factory = new DataAnnotationsValidatorFactory(adapterFactory, adapter);
        }
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     return new GreaterThanOrEqual
     {
         Value = ((GreaterThanOrEqualValidator)propertyValidator).ValueToCompare,
         Message = propertyValidator.GetErrorMessageFor(propertyName)
     };
 }
Ejemplo n.º 9
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     return new LessThan
     {
         Value = ((LessThanValidator)propertyValidator).ValueToCompare,
         Message = propertyValidator.GetErrorMessageFor(propertyName)
     };
 }
        public RequiredFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
            : base(metadata, controllerContext, rule, validator)
        {
            bool isNonNullableValueType = !TypeAllowsNullValue(metadata.ModelType);
            bool nullWasSpecified = metadata.Model == null;

            ShouldValidate = isNonNullableValueType && nullWasSpecified;
        }
Ejemplo n.º 11
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     var emailRule = new Email
     {
         Message = propertyValidator.GetErrorMessageFor(propertyName)
     };
     return emailRule;
 }
Ejemplo n.º 12
0
 public Rule GeneratorFrom(IPropertyValidator propertyValidator)
 {
     return new GreaterThan
     {
         Value = ((GreaterThanValidator)propertyValidator).ValueToCompare,
         Message = propertyValidator.ErrorMessageSource.GetString()
     };
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return new StringLengthValidationRule(
         base.FormatMessage(rule, validator),
         base.GetMemberNames(rule),
         ((ILengthValidator)validator).Min,
         ((ILengthValidator)validator).Max);
 }
Ejemplo n.º 14
0
 public Rule GeneratorFrom(IPropertyValidator propertyValidator)
 {
     var emailRule = new Email
     {
         Message = propertyValidator.ErrorMessageSource.GetString()
     };
     return emailRule;
 }
Ejemplo n.º 15
0
 public Rule GeneratorFrom(IPropertyValidator propertyValidator)
 {
     return new LessThanOrEqual
     {
         Value = ((LessThanOrEqualValidator)propertyValidator).ValueToCompare,
         Message = propertyValidator.ErrorMessageSource.GetString()
     };
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return new ComparisonValidationRule(
         base.FormatMessage(rule, validator),
         base.GetMemberNames(rule),
         ComparisonOperator.LessThan,
         ((LessThanValidator)validator).ValueToCompare);
 }
Ejemplo n.º 17
0
 public Rule GeneratorFrom(IPropertyValidator propertyValidator)
 {
     var rule = new Regex
     {
         Message = propertyValidator.ErrorMessageSource.GetString(),
         Expression = ((IRegularExpressionValidator)propertyValidator).Expression
     };
     return rule;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Get the formatted error message of the validator.
 /// </summary>
 /// <returns>A formatted error message string.</returns>
 protected virtual Func<string, string> FormatMessage(PropertyRule rule, IPropertyValidator validator)
 {
     return displayName =>
     {
         return new MessageFormatter()
             .AppendPropertyName(displayName ?? rule.GetDisplayName())
             .BuildMessage(validator.ErrorMessageSource.GetString());
     };
 }
Ejemplo n.º 19
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     var rule = new Regex
     {
         Message = propertyValidator.GetErrorMessageFor(propertyName),
         Expression = ((IRegularExpressionValidator)propertyValidator).Expression
     };
     return rule;
 }
 public SimpleUnitaryClientSideValidator(ModelMetadata metadata,
                                         ControllerContext controllerContext,
                                         PropertyRule rule,
                                         IPropertyValidator validator,
                                         string validationType)
     : base(metadata, controllerContext, rule, validator)
 {
     _validationType = validationType;
 }
Ejemplo n.º 21
0
 public Rule GeneratorFrom(string propertyName, IPropertyValidator propertyValidator)
 {
     return new Length
         {
             Min = ((ILengthValidator)propertyValidator).Min,
             Max = ((ILengthValidator)propertyValidator).Max,
             Message = propertyValidator.GetErrorMessageFor(propertyName)
         };
 }
        private ModelValidator GetModelValidator(ModelMetadata meta, ControllerContext context, IPropertyValidator propertyValidator)
        {
            var type = propertyValidator.GetType();
            var factory = validatorFactories
                .Where(x => x.Key.IsAssignableFrom(type))
                .Select(x => x.Value)
                .FirstOrDefault() ?? FluentValidationPropertyValidator.Create;

            return factory(meta, context, propertyValidator);
        }
Ejemplo n.º 23
0
 private static IValidator GetValidator(IPropertyValidator inlineval, IValidator val)
 {
     var valtype = inlineval.GetType();
     if (valtype == typeof (ChildCollectionValidatorAdaptor))
         val = ((ChildCollectionValidatorAdaptor) inlineval).Validator;
     else if (valtype == typeof (ChildValidatorAdaptor))
         val = ((ChildValidatorAdaptor) inlineval).Validator;
     else if (valtype == typeof (DelegatingValidator))
         val = GetValidator(((DelegatingValidator) inlineval).InnerValidator, val);
     return val;
 }
        /// <summary>
        /// Creates a <see cref="IFluentAdapter"/> instance based on the provided <paramref name="rule"/> and <paramref name="propertyValidator"/>.
        /// </summary>
        /// <param name="rule">The <see cref="PropertyRule"/> for which the adapter should be created.</param>
        /// <param name="propertyValidator">The <see cref="IPropertyValidator"/> for which the adapter should be created.</param>
        /// <returns>An <see cref="IFluentAdapter"/> instance.</returns>
        public IFluentAdapter Create(PropertyRule rule, IPropertyValidator propertyValidator)
        {
            Func<PropertyRule, IPropertyValidator, IFluentAdapter> factory;

            if (!factories.TryGetValue(propertyValidator.GetType(), out factory))
            {
                factory = (a, d) => new FluentAdapter("Custom", rule, propertyValidator);
            }

            return factory(rule, propertyValidator);
        }
		public FluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator) : base(metadata, controllerContext) {
			this.Validator = validator;

			// Build a new rule instead of the one passed in.
			// We do this as the rule passed in will not have the correct properties defined for standalone validation.
			// We also want to ensure we copy across the CustomPropertyName and RuleSet, if specified. 
			Rule = new PropertyRule(null, x => metadata.Model, null, null, metadata.ModelType, null) {
				PropertyName = metadata.PropertyName,
				DisplayName = rule == null ? null : rule.DisplayName,
				RuleSet = rule == null ? null : rule.RuleSet
			};
		}
        private ModelValidator GetModelValidator(ModelMetadata meta, IEnumerable<ModelValidatorProvider> validatorProviders, PropertyRule rule, IPropertyValidator propertyValidator)
        {
            //var type = propertyValidator.GetType();

            FluentValidationHttpModelValidationFactory factory =
                //validatorFactories
                //.Where(x => x.Key.IsAssignableFrom(type))
                //.Select(x => x.Value)
                //.FirstOrDefault()
                //??
                ((metadata, controllerContext, description, validator) => new FluentValidationHttpPropertyValidator(metadata, controllerContext, description, validator));

            return factory(meta, validatorProviders, rule, propertyValidator);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
        /// </summary>
        /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
        public override IEnumerable<ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
        {
            yield return new ComparisonValidationRule(
                base.FormatMessage(rule, validator),
                base.GetMemberNames(rule),
                ComparisonOperator.GreaterThan,
                ((ExclusiveBetweenValidator)validator).From);

            yield return new ComparisonValidationRule(
                base.FormatMessage(rule, validator),
                base.GetMemberNames(rule),
                ComparisonOperator.LessThan,
                ((ExclusiveBetweenValidator)validator).To);
        }
Ejemplo n.º 28
0
        public ValidatorPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
            : base(metadata, controllerContext, rule, validator)
        {
            ShouldValidate = false;

            var model = controllerContext.Controller.ViewData.Model;
            if (validator is PropertyValidatorWithDynamicState)
            {
                
                DynamicState = new DynamicState(model, ((PropertyValidatorWithDynamicState)validator).Properties);
            }
            else
            {
                DynamicState = new DynamicState(model);
            }
        }
#pragma warning restore 1591 // Xml Comments

        void GenerateFor(ValidationMetaData metaData, string property, IPropertyValidator validator)
        {
            var validatorType = validator.GetType();
            var types = new List<Type>();
            types.Add(validatorType);
            types.AddRange(validatorType.GetInterfaces());
            foreach (var type in types)
            {
                if (_generatorsByType.ContainsKey(type))
                {
                    var rule = _generatorsByType[type].GeneratorFrom(validator);
                    var ruleName = rule.GetType().Name.ToCamelCase();
                    var propertyName = property.ToCamelCase();
                    metaData[propertyName][ruleName] = rule;
                }
            }
        }
        public DataAnnotationsValidatorFixture()
        {
            this.propertyValidator1 =
                A.Fake<IPropertyValidator>();

            this.propertyValidator2 =
                A.Fake<IPropertyValidator>();

            this.validatableObjectAdapter =
                A.Fake<IValidatableObjectAdapter>();

            this.validatorFactory =
                A.Fake<IPropertyValidatorFactory>();

            A.CallTo(() => this.validatorFactory.GetValidators(typeof(ModelUnderTest)))
               .Returns(new[] { this.propertyValidator1, this.propertyValidator2 });

            this.validator =
                new DataAnnotationsValidator(typeof(ModelUnderTest), this.validatorFactory, this.validatableObjectAdapter);
        }
Ejemplo n.º 31
0
 public PropertyValidatorResult(IPropertyValidator propertyValidator, string displayName)
 {
     PropertyValidator = propertyValidator;
     DisplayName       = displayName;
 }
 /// <summary>Initializes a new instance of the FluentValidation.Mvc.RegularExpressionFluentValidationPropertyValidator class.</summary>
 ///
 /// <param name="metadata">         The metadata.</param>
 /// <param name="controllerContext">Context for the controller.</param>
 /// <param name="rule">             The rule.</param>
 /// <param name="validator">        The validator.</param>
 public RegularExpressionFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
     : base(metadata, controllerContext, rule, validator)
 {
     ShouldValidate = false;
 }
Ejemplo n.º 33
0
 public LengthClientValidator(PropertyRule rule, IPropertyValidator validator)
     : base(rule, validator)
 {
 }
 public RangeClientValidator(PropertyRule rule, IPropertyValidator validator) : base(rule, validator)
 {
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Invokes the validator asynchronously
        /// </summary>
        /// <param name="context"></param>
        /// <param name="validator"></param>
        /// <param name="propertyName"></param>
        /// <param name="cancellation"></param>
        /// <returns></returns>
        protected override async Task <IEnumerable <ValidationFailure> > InvokePropertyValidatorAsync(IValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                propertyName = InferPropertyName(Expression);
            }

            PropertyValidatorContext propertyContext;

            // TODO: For FV10 this will come as a parameter rather than in RootContextData.
            if (context.RootContextData.TryGetValue("__FV_CurrentAccessor", out var a) && a is Lazy <object> accessor)
            {
                propertyContext = new PropertyValidatorContext(context, this, propertyName, accessor);
            }
            else
            {
#pragma warning disable 618
                propertyContext = new PropertyValidatorContext(context, this, propertyName);
#pragma warning restore 618
            }

            if (!validator.Options.InvokeCondition(propertyContext))
            {
                return(Enumerable.Empty <ValidationFailure>());
            }
            if (!await validator.Options.InvokeAsyncCondition(propertyContext, cancellation))
            {
                return(Enumerable.Empty <ValidationFailure>());
            }

            var collectionPropertyValue = propertyContext.PropertyValue as IEnumerable <TElement>;

            if (collectionPropertyValue != null)
            {
                if (string.IsNullOrEmpty(propertyName))
                {
                    throw new InvalidOperationException("Could not automatically determine the property name ");
                }

                var actualContext = ValidationContext <T> .GetFromNonGenericContext(context);

                var validatorTasks = collectionPropertyValue.Select(async(element, index) => {
                    if (Filter != null && !Filter(element))
                    {
                        return(Enumerable.Empty <ValidationFailure>());
                    }

                    string indexer             = index.ToString();
                    bool useDefaultIndexFormat = true;

                    if (IndexBuilder != null)
                    {
                        indexer = IndexBuilder(context.InstanceToValidate, collectionPropertyValue, element, index);
                        useDefaultIndexFormat = false;
                    }

                    ValidationContext <T> newContext = actualContext.CloneForChildCollectionValidator(actualContext.InstanceToValidate, preserveParentContext: true);
                    newContext.PropertyChain.Add(propertyName);
                    newContext.PropertyChain.AddIndexer(indexer, useDefaultIndexFormat);

                    object valueToValidate = element;

#pragma warning disable 618
                    if (Transformer != null)
                    {
                        valueToValidate = Transformer(element);
                    }
#pragma warning restore 618

                    var newPropertyContext = new PropertyValidatorContext(newContext, this, newContext.PropertyChain.ToString(), valueToValidate);
                    newPropertyContext.MessageFormatter.AppendArgument("CollectionIndex", index);

                    return(await validator.ValidateAsync(newPropertyContext, cancellation));
                });

                var results = new List <ValidationFailure>();

                foreach (var task in validatorTasks)
                {
                    var failures = await task;
                    results.AddRange(failures);
                }

                return(results);
            }

            return(Enumerable.Empty <ValidationFailure>());
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Gets whether or not the adapter can handle the provided <see cref="IPropertyValidator"/> instance.
 /// </summary>
 /// <param name="validator">The <see cref="IPropertyValidator"/> instance to check for compatability with the adapter.</param>
 /// <returns><see langword="true" /> if the adapter can handle the validator, otherwise <see langword="false" />.</returns>
 public override bool CanHandle(IPropertyValidator validator)
 {
     return(validator is ExclusiveBetweenValidator);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
        /// </summary>
        /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
        public override IEnumerable <ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
        {
            yield return(new ComparisonValidationRule(
                             base.FormatMessage(rule, validator),
                             base.GetMemberNames(rule),
                             ComparisonOperator.GreaterThan,
                             ((ExclusiveBetweenValidator)validator).From));

            yield return(new ComparisonValidationRule(
                             base.FormatMessage(rule, validator),
                             base.GetMemberNames(rule),
                             ComparisonOperator.LessThan,
                             ((ExclusiveBetweenValidator)validator).To));
        }
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable <ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return(new RegexValidationRule(
                      base.FormatMessage(rule, validator),
                      base.GetMemberNames(rule),
                      ((IEmailValidator)validator).Expression));
 }
Ejemplo n.º 39
0
 public BackwardsCompatibilityValidatorAdaptor(IPropertyValidator <T, TProperty> obsoleteValidator)
     : base(null as string)
 {
     this.obsoleteValidator = obsoleteValidator;
 }
Ejemplo n.º 40
0
 public static IRuleBuilderOptions <T, TProperty> SetValidator <T, TProperty>(this IRuleBuilder <T, TProperty> rule, IPropertyValidator <T, TProperty> validator)
 {
     return(rule.SetValidator(new BackwardsCompatibilityValidatorAdaptor <T, TProperty>(validator)));
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Get the <see cref="ModelValidationRule"/> instances that are mapped from the fluent validation rule.
 /// </summary>
 /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="ModelValidationRule"/> instances.</returns>
 public override IEnumerable <ModelValidationRule> GetRules(PropertyRule rule, IPropertyValidator validator)
 {
     yield return(new ModelValidationRule(
                      "Custom",
                      base.FormatMessage(rule, validator),
                      base.GetMemberNames(rule)));
 }
Ejemplo n.º 42
0
 /// <summary>
 /// Gets whether or not the adapter can handle the provided <see cref="IPropertyValidator"/> instance.
 /// </summary>
 /// <param name="validator">The <see cref="IPropertyValidator"/> instance to check for compatibility with the adapter.</param>
 /// <returns><see langword="true" /> if the adapter can handle the validator, otherwise <see langword="false" />.</returns>
 public override bool CanHandle(IPropertyValidator validator)
 {
     return(false);
 }
 public StringLengthFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
     : base(metadata, controllerContext, rule, validator)
 {
     ShouldValidate = false;
 }
 public CreditCardClientValidator(PropertyRule rule, IPropertyValidator validator) : base(rule, validator)
 {
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Invokes the validator asynchronously
        /// </summary>
        /// <param name="context"></param>
        /// <param name="validator"></param>
        /// <param name="propertyName"></param>
        /// <param name="cancellation"></param>
        /// <returns></returns>
        protected override Task <IEnumerable <ValidationFailure> > InvokePropertyValidatorAsync(ValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation)
        {
            var propertyContext     = new PropertyValidatorContext(context, this, propertyName);
            var results             = new List <ValidationFailure>();
            var delegatingValidator = validator as IDelegatingValidator;

            if (delegatingValidator == null || delegatingValidator.CheckCondition(propertyContext.Instance))
            {
                var collectionPropertyValue = propertyContext.PropertyValue as IEnumerable <TProperty>;

                if (collectionPropertyValue != null)
                {
                    var validators = collectionPropertyValue.Select((v, count) => {
                        var newContext = context.CloneForChildValidator(context.InstanceToValidate);
                        newContext.PropertyChain.Add(propertyName);
                        newContext.PropertyChain.AddIndexer(count);

                        var newPropertyContext = new PropertyValidatorContext(newContext, this, newContext.PropertyChain.ToString(), v);

                        return(validator.ValidateAsync(newPropertyContext, cancellation)
                               .Then(fs => results.AddRange(fs)));
                    });


                    return
                        (TaskHelpers.Iterate(
                             validators,
                             cancellationToken: cancellation
                             ).Then(() => results.AsEnumerable(), runSynchronously: true));
                }
            }

            return(TaskHelpers.FromResult(Enumerable.Empty <ValidationFailure>()));
        }
Ejemplo n.º 46
0
 public ClientValidatorBase(PropertyRule rule, IPropertyValidator validator)
 {
     this.Validator = validator;
     this.Rule      = rule;
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Invokes the validator asynchronously
 /// </summary>
 /// <param name="context"></param>
 /// <param name="validator"></param>
 /// <param name="propertyName"></param>
 /// <param name="cancellation"></param>
 /// <returns></returns>
 protected virtual Task <IEnumerable <ValidationFailure> > InvokePropertyValidatorAsync(ValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation)
 {
     return(validator.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation));
 }
Ejemplo n.º 48
0
 public RequiredClientValidator(PropertyRule rule, IPropertyValidator validator) : base(rule, validator)
 {
 }
 protected AbstractComparisonFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule propertyDescription, IPropertyValidator validator) : base(metadata, controllerContext, propertyDescription, validator)
 {
     ShouldValidate = false;
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Sets the validator associated with the rule.
 /// </summary>
 /// <param name="validator">The validator to set</param>
 /// <returns></returns>
 public RuleBuilder <T, TProperty> SetValidator(IPropertyValidator validator)
 {
     validator.Guard("Cannot pass a null validator to SetValidator.");
     rule.AddValidator(validator);
     return(this);
 }
Ejemplo n.º 51
0
 public static IRuleBuilderOptions <T, TProperty> Must <T, TProperty>(
     this IRuleBuilder <T, TProperty> ruleBuilder, IPropertyValidator validator)
 => ruleBuilder.SetValidator(validator);
Ejemplo n.º 52
0
        /// <summary>
        /// Invokes a property validator using the specified validation context.
        /// </summary>
        protected virtual IEnumerable <ValidationFailure> InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, string propertyName)
        {
            var propertyContext = new PropertyValidatorContext(context, this, propertyName);

            return(validator.Validate(propertyContext));
        }
Ejemplo n.º 53
0
 public AnnotationDataValidator(IPropertyValidator propertyValidator)
 {
     _propertyValidator = propertyValidator ?? throw new ArgumentNullException(nameof(propertyValidator));
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Adds a validator to the rule.
 /// </summary>
 public void AddValidator(IPropertyValidator validator)
 {
     CurrentValidator = validator;
     validators.Add(validator);
 }
 /// <summary>
 /// Gets whether or not the adapter can handle the provided <see cref="IPropertyValidator"/> instance.
 /// </summary>
 /// <param name="validator">The <see cref="IPropertyValidator"/> instance to check for compatibility with the adapter.</param>
 /// <returns><see langword="true" /> if the adapter can handle the validator, otherwise <see langword="false" />.</returns>
 public override bool CanHandle(IPropertyValidator validator)
 {
     return(validator is EmailValidator);
 }
        public RequiredFluentValidationPropertyValidator(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator) : base(metadata, controllerContext, rule, validator)
        {
            bool isNonNullableValueType = !TypeAllowsNullValue(metadata.ModelType);
            bool nullWasSpecified       = metadata.Model == null;

            ShouldValidate = isNonNullableValueType && nullWasSpecified;
        }
Ejemplo n.º 57
0
 internal RuleComponent(IAsyncPropertyValidator <T, TProperty> asyncPropertyValidator, IPropertyValidator <T, TProperty> propertyValidator)
 {
     _asyncPropertyValidator = asyncPropertyValidator;
     _propertyValidator      = propertyValidator;
 }
Ejemplo n.º 58
0
 internal RuleComponent(IPropertyValidator <T, TProperty> propertyValidator)
 {
     _propertyValidator = propertyValidator;
 }
 public OnFailureValidator(IPropertyValidator innerValidator, Action <T, PropertyValidatorContext> onFailure)
 {
     _innerValidator  = innerValidator;
     _onFailureSimple = onFailure;
 }
        protected virtual IClientModelValidator GetModelValidator(ClientValidatorProviderContext context, PropertyRule rule, IPropertyValidator propertyValidator)
        {
            var type = propertyValidator.GetType();

            var factory = _validatorFactories
                          .Where(x => x.Key.IsAssignableFrom(type))
                          .Select(x => x.Value)
                          .FirstOrDefault();

            if (factory != null)
            {
                var  ruleSetToGenerateClientSideRules = RuleSetForClientSideMessagesAttribute.GetRuleSetsForClientValidation(_httpContextAccessor?.HttpContext);
                bool executeDefaultRule = (ruleSetToGenerateClientSideRules.Contains("default", StringComparer.OrdinalIgnoreCase) && (rule.RuleSets.Length == 0 || rule.RuleSets.Contains("default", StringComparer.OrdinalIgnoreCase)));
                bool shouldExecute      = ruleSetToGenerateClientSideRules.Intersect(rule.RuleSets, StringComparer.OrdinalIgnoreCase).Any() || executeDefaultRule;

                if (shouldExecute)
                {
                    return(factory.Invoke(context, rule, propertyValidator));
                }
            }

            return(null);
        }