Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var order = new Order
            {
                Product = new Product {
                    Name = "Widget", MinQuantity = 5, MaxQuantity = 100
                },
                Quantity = 50
            };

            var runner = new ValidatorRunner(new CachedValidationRegistry());

            if (runner.IsValid(order))
            {
                Console.WriteLine("The order is valid!");
            }
            else
            {
                ErrorSummary summary = runner.GetErrorSummary(order);
                foreach (var invalidProperty in summary.InvalidProperties)
                {
                    Console.WriteLine("{0} is invalid because:", invalidProperty);
                    foreach (var error in summary.GetErrorsForProperty(invalidProperty))
                    {
                        Console.WriteLine("\t * {0}", error);
                    }
                }
            }

            Console.ReadLine();
        }
Ejemplo n.º 2
0
		/// <summary>
		/// Performs the actual validation. Override this one to perform custom validation.
		/// </summary>
		/// <param name="objectToValidate"></param>
		/// <param name="includeProperties"></param>
		protected virtual void PerformValidation(T objectToValidate, ICollection<string> includeProperties)
		{
			// Check the validatorrunner.
			if (this._validatorRunner == null)
			{
				throw new InvalidOperationException("Unable to validate the object, because there is no ValidationRunner available.");
			}
			if (!this._validatorRunner.IsValid(objectToValidate))
			{
				// Check if the error properties match any of the given properties. If not return true (invalid object, but
				// the caller didn't care about the invalid properties.
				ErrorSummary errorSummary = this._validatorRunner.GetErrorSummary(objectToValidate);
				if (errorSummary.HasError)
				{
					foreach (string property in errorSummary.InvalidProperties)
					{
						if (ShouldValidateProperty(property, includeProperties))
						{
							//hasErrorWeCareAbout = true;
							string[] errorsForProperty = errorSummary.GetErrorsForProperty(property);
							foreach (string error in errorsForProperty)
							{
								AddError(property, error, false);
							}
						}
					}
				}
			}
		}
Ejemplo n.º 3
0
        /// <summary>
        /// Registers the error message returned from an object validator
        /// as an error message for each individual indexed property.
        /// </summary>
        /// <param name="validator">The validator.</param>
        /// <param name="errors">The errors.</param>
        private void RegisterObjectValidatorErrorMessages(ObjectValidator validator, ErrorSummary errors)
        {
            ErrorSummary objectErrors = validator.ErrorSummary;

            foreach (string property in objectErrors.InvalidProperties)
            {
                foreach (string message in objectErrors.GetErrorsForProperty(property))
                {
                    errors.RegisterErrorMessage(validator.FriendlyName + "." + property, message);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates a string representation of the error summary.
        /// </summary>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public static string  CreateSummary(ErrorSummary errors)
        {
            StringBuilder builder = new StringBuilder();

            foreach (string property in errors.InvalidProperties)
            {
                builder.Append("    - ").Append(property).Append(": ");
                builder.Append(string.Join(",", errors.GetErrorsForProperty(property)));
                builder.Append(Environment.NewLine);
            }
            return(builder.ToString());
        }
Ejemplo n.º 5
0
        public void ExecutesSelfValidationByDefault()
        {
            SelfValidationTestTarget target = new SelfValidationTestTarget();

            Assert.IsFalse(runner.IsValid(target));
            ErrorSummary errors = runner.GetErrorSummary(target);

            Assert.IsTrue(errors.HasError);
            Assert.AreEqual(1, errors.ErrorsCount);
            string[] errorsForKey = errors.GetErrorsForProperty("errorKey");
            Assert.AreEqual(1, errorsForKey.Length);
            Assert.AreEqual("errorMessage", errorsForKey[0]);
        }
Ejemplo n.º 6
0
        public void ExecutesCustomContributors()
        {
            ValidatorRunner runnerWithContributor = new ValidatorRunner(true, new CachedValidationRegistry(),
                                                                        new IValidationContributor[] { new AlwaysErrorContributor() });

            object target = new object();

            Assert.IsFalse(runnerWithContributor.IsValid(target));
            ErrorSummary errors = runnerWithContributor.GetErrorSummary(target);

            Assert.IsTrue(errors.HasError);
            Assert.AreEqual(1, errors.ErrorsCount);
            string[] errorsForKey = errors.GetErrorsForProperty("someKey");
            Assert.AreEqual(1, errorsForKey.Length);
            Assert.AreEqual("error", errorsForKey[0]);
        }
Ejemplo n.º 7
0
 private void CheckForValidationFailures(object instance, string prefix, ErrorSummary summary)
 {
     if (validator == null)
     {
         return;
     }
     if (!validator.IsValid(instance))
     {
         summary.RegisterErrorsFrom(validator.GetErrorSummary(instance));
         foreach (string invalidProperty in summary.InvalidProperties)
         {
             foreach (string errorMessage in summary.GetErrorsForProperty(invalidProperty))
             {
                 errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
             }
         }
     }
 }
        private static void AddModelErrors(ModelStateDictionary modelState, ErrorSummary errorSummary)
        {
            if (errorSummary == null)
            {
                throw new ArgumentNullException("errorSummary");
            }

            var errorInfos = from property in errorSummary.InvalidProperties
                             from message in errorSummary.GetErrorsForProperty(property)
                             select new
            {
                PropertyName = property,
                ErrorMessage = message
            };

            foreach (var errorInfo in errorInfos)
            {
                modelState.AddModelError(errorInfo.PropertyName, errorInfo.ErrorMessage);
            }
        }
        /// <summary>
        /// Performs the fields validation for the specified action.
        /// </summary>
        /// <param name="runWhen">Use validators appropriate to the action being performed.</param>
        /// <returns>True if no validation error was found</returns>
        public virtual bool IsValid(RunWhen runWhen)
        {
            failedProperties = new Dictionary <PropertyInfo, ArrayList>();

            // first check if the object itself is valid
            bool returnValue = Runner.IsValid(ARObjectInstance, runWhen);

            // then check the components that are properties if the object
            foreach (PropertyInfo propinfo in GetNestedPropertiesToValidate(ARObjectInstance))
            {
                object propval = propinfo.GetValue(ARObjectInstance, null);

                if (propval != null)
                {
                    bool propValid = Runner.IsValid(propval, runWhen);
                    if (!propValid)
                    {
                        ErrorSummary propSummary = Runner.GetErrorSummary(propval);
                        string[]     propErrors  = propSummary.GetErrorsForProperty(propinfo.Name);
                        failedProperties.Add(propinfo, new ArrayList(propErrors));
                    }
                    returnValue &= propValid;
                }
            }

            if (!returnValue)
            {
                Type         type    = ARObjectInstance.GetType();
                ErrorSummary summary = Runner.GetErrorSummary(ARObjectInstance);

                foreach (string property in summary.InvalidProperties)
                {
                    string[] errors = summary.GetErrorsForProperty(property);
                    failedProperties.Add(type.GetProperty(property), new ArrayList(errors));
                }
            }

            return(returnValue);
        }
Ejemplo n.º 10
0
        private void CheckForValidationFailures(object instance, string prefix, Node node, ErrorSummary summary)
        {
            if (validator == null)
            {
                return;
            }
            if (!validator.IsValid(instance))
            {
                ErrorSummary errorSummaryFromValidator = validator.GetErrorSummary(instance);
                foreach (string invalidProperty in errorSummaryFromValidator.InvalidProperties)
                {
                    if (ShouldIgnoreProperty(string.Format("{0}.{1}", node.FullName, invalidProperty)))
                    {
                        continue;
                    }

                    foreach (string errorMessage in errorSummaryFromValidator.GetErrorsForProperty(invalidProperty))
                    {
                        summary.RegisterErrorMessage(invalidProperty, errorMessage);
                        errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
                    }
                }
            }
        }
Ejemplo n.º 11
0
		private void CheckForValidationFailures(object instance, string prefix, ErrorSummary summary)
		{
			if (validator == null)
			{
				return;
			}
			if (!validator.IsValid(instance))
			{
				summary.RegisterErrorsFrom(validator.GetErrorSummary(instance));
				foreach (string invalidProperty in summary.InvalidProperties)
				{
					foreach (string errorMessage in summary.GetErrorsForProperty(invalidProperty))
					{
						errors.Add(new DataBindError(prefix, invalidProperty, errorMessage));
					}
				}
			}
		}