/// <summary>Enumerates validate in this collection.</summary>
        ///
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns>
        public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
            if (context.Rule.Member == null) {
                throw new InvalidOperationException(string.Format("Nested validators can only be used with Member Expressions."));
            }

            var collection = context.PropertyValue as IEnumerable;

            if (collection == null) {
                yield break;
            }

            int count = 0;
            
            var predicate = Predicate ?? (x => true);

            foreach (var element in collection) {

                if(element == null || !(predicate(element))) {
                    // If an element in the validator is null then we want to skip it to prevent NullReferenceExceptions in the child validator.
                    // We still need to update the counter to ensure the indexes are correct.
                    count++;
                    continue;
                }

                var newContext = context.ParentContext.CloneForChildValidator(element);
                newContext.PropertyChain.Add(context.Rule.Member);
                newContext.PropertyChain.AddIndexer(count++);

                var results = childValidator.Validate(newContext).Errors;

                foreach (var result in results) {
                    yield return result;
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            var value = context.PropertyValue as string;

            if (value == null) {
                return true;
            }

            value = value.Replace("-", "");

            int checksum = 0;
            bool evenDigit = false;

            // http://www.beachnet.com/~hstiles/cardtype.html
            foreach (char digit in value.Reverse()) {
                if (!char.IsDigit(digit)) {
                    return false;
                }

                int digitValue = (digit - '0') * (evenDigit ? 2 : 1);
                evenDigit = !evenDigit;

                while (digitValue > 0) {
                    checksum += digitValue % 10;
                    digitValue /= 10;
                }
            }

            return (checksum % 10) == 0;
        }
Ejemplo n.º 3
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            if (!predicate(context.Instance, context.PropertyValue, context)) {
                return false;
            }

            return true;
        }
        private IComparable GetComparisonValue(PropertyValidatorContext context) {
            if(valueToCompareFunc != null) {
                return (IComparable)valueToCompareFunc(context.Instance);
            }

            return (IComparable)ValueToCompare;
        }
Ejemplo n.º 5
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            if (context.PropertyValue == null) return true;

            if (!regex.IsMatch((string)context.PropertyValue)) {
                return false;
            }

            return true;
        }
Ejemplo n.º 6
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            if (context.PropertyValue == null
                || IsInvalidString(context.PropertyValue)
                || IsEmptyCollection(context.PropertyValue)
                || Equals(context.PropertyValue, defaultValueForType)) {
                return false;
            }

            return true;
        }
Ejemplo n.º 7
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            var comparisonValue = GetComparisonValue(context);
            bool success = !Compare(comparisonValue, context.PropertyValue);

            if (!success) {
                context.MessageFormatter.AppendArgument("PropertyValue", context.PropertyValue);
                return false;
            }

            return true;
        }
Ejemplo n.º 8
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            int length = context.PropertyValue == null ? 0 : context.PropertyValue.ToString().Length;

            if (length < Min || length > Max) {
                context.MessageFormatter
                    .AppendArgument("MinLength", Min)
                    .AppendArgument("MaxLength", Max)
                    .AppendArgument("TotalLength", length);

                return false;
            }

            return true;
        }
        /// <summary>Query if 'value' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected sealed override bool IsValid(PropertyValidatorContext context) {
            if(context.PropertyValue == null) {
                // If we're working with a nullable type then this rule should not be applied.
                // If you want to ensure that it's never null then a NotNull rule should also be applied. 
                return true;
            }
            
            var value = GetComparisonValue(context);

            if (!IsValid((IComparable)context.PropertyValue, value)) {
                context.MessageFormatter.AppendArgument("ComparisonValue", value);
                return false;
            }

            return true;
        }
        /// <summary>When implemented in a derived class, validates the object.</summary>
        ///
        /// <param name="container">The container.</param>
        ///
        /// <returns>A list of validation results.</returns>
		public override IEnumerable<ModelValidationResult> Validate(object container) {
			if (ShouldValidate) {
				var fakeRule = new PropertyRule(null, x => Metadata.Model, null, null, Metadata.ModelType, null) {
					PropertyName = Metadata.PropertyName,
					DisplayName = Rule == null ? null : Rule.DisplayName,
				};

				var fakeParentContext = new ValidationContext(container);
				var context = new PropertyValidatorContext(fakeParentContext, fakeRule, Metadata.PropertyName);
				var result = Validator.Validate(context);

				foreach (var failure in result) {
					yield return new ModelValidationResult { Message = failure.ErrorMessage };
				}
			}
		}
Ejemplo n.º 11
0
        /// <summary>Query if 'context' is valid.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>true if valid, false if not.</returns>
        protected override bool IsValid(PropertyValidatorContext context) {
            var propertyValue = (IComparable)context.PropertyValue;

            // If the value is null then we abort and assume success.
            // This should not be a failure condition - only a NotNull/NotEmpty should cause a null to fail.
            if (propertyValue == null) return true;

            if (propertyValue.CompareTo(From) < 0 || propertyValue.CompareTo(To) > 0) {

                context.MessageFormatter
                    .AppendArgument("From", From)
                    .AppendArgument("To", To)
                    .AppendArgument("Value", context.PropertyValue);

                return false;
            }
            return true;
        }
Ejemplo n.º 12
0
        /// <summary>Enumerates validate in this collection.</summary>
        ///
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns>
        public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
            if (context.Rule.Member == null) {
                throw new InvalidOperationException(string.Format("Nested validators can only be used with Member Expressions."));
            }

            var instanceToValidate = context.PropertyValue;

            if (instanceToValidate == null) {
                return Enumerable.Empty<ValidationFailure>();
            }

            var validator = GetValidator(context);

            if(validator == null) {
                return Enumerable.Empty<ValidationFailure>();
            }

            var newContext = CreateNewValidationContextForChildValidator(instanceToValidate, context);
            var results = validator.Validate(newContext).Errors;

            return results;
        }
Ejemplo n.º 13
0
        /// <summary>Enumerates validate in this collection.</summary>
        ///
        /// <param name="context">The context.</param>
        ///
        /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns>
        public virtual IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
            context.MessageFormatter.AppendPropertyName(context.PropertyDescription);

            if (!IsValid(context)) {
                return new[] { CreateValidationError(context) };
            }

            return Enumerable.Empty<ValidationFailure>();
        }
Ejemplo n.º 14
0
 /// <summary>Creates new validation context for child validator.</summary>
 ///
 /// <param name="instanceToValidate">The instance to validate.</param>
 /// <param name="context">           The context.</param>
 ///
 /// <returns>The new new validation context for child validator.</returns>
 protected ValidationContext CreateNewValidationContextForChildValidator(object instanceToValidate, PropertyValidatorContext context) {
     var newContext = context.ParentContext.CloneForChildValidator(instanceToValidate);
     newContext.PropertyChain.Add(context.Rule.Member);
     return newContext;
 }
Ejemplo n.º 15
0
 /// <summary>Gets a validator.</summary>
 ///
 /// <param name="context">The context.</param>
 ///
 /// <returns>The validator.</returns>
 protected virtual IValidator GetValidator(PropertyValidatorContext context) {
     return Validator;
 }
Ejemplo n.º 16
0
 /// <summary>Enumerates validate in this collection.</summary>
 ///
 /// <param name="context">The context.</param>
 ///
 /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns>
 public abstract IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context);
Ejemplo n.º 17
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) {
            context.MessageFormatter.AppendAdditionalArguments(
                customFormatArgs.Select(func => func(context.Instance)).ToArray()
            );

            string error = context.MessageFormatter.BuildMessage(errorSource.GetString());

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

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

            return failure;
        }
Ejemplo n.º 18
0
 /// <summary>Query if 'context' is valid.</summary>
 ///
 /// <param name="context">The validator context.</param>
 ///
 /// <returns>true if valid, false if not.</returns>
 protected abstract bool IsValid(PropertyValidatorContext context);
Ejemplo n.º 19
0
        private object GetComparisonValue(PropertyValidatorContext context) {
            if (func != null) {
                return func(context.Instance);
            }

            return ValueToCompare;
        }
Ejemplo n.º 20
0
 /// <summary>Enumerates validate in this collection.</summary>
 ///
 /// <param name="context">The context.</param>
 ///
 /// <returns>An enumerator that allows foreach to be used to process validate in this collection.</returns>
 public IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
     if (condition(context.Instance)) {
         return InnerValidator.Validate(context);
     }
     return Enumerable.Empty<ValidationFailure>();
 }
Ejemplo n.º 21
0
 /// <summary>Query if 'context' is valid.</summary>
 ///
 /// <param name="context">The context.</param>
 ///
 /// <returns>true if valid, false if not.</returns>
 protected override bool IsValid(PropertyValidatorContext context) {
     if (context.PropertyValue == null) {
         return false;
     }
     return true;
 }