private static ValidationResult Validate(ValidationContext context)
        {
            var properties = context.ObjectType.GetProperties();

            if (context.ObjectInstance is IValidatableObject)
            {
                IValidatableObject valid = (IValidatableObject)context.ObjectInstance;
                var validationResults    = valid.Validate(context);
                if (validationResults != null && validationResults.Count() > 0)
                {
                    return(valid.Validate(context).FirstOrDefault());
                }
            }

            foreach (var property in properties)
            {
                var validationAttributes = property.GetCustomAttributes(false).OfType <ValidationAttribute>();
                foreach (var attribute in validationAttributes)
                {
                    bool isValid = attribute.IsValid(property.GetValue(context.ObjectInstance));
                    if (!isValid)
                    {
                        return(new ValidationResult(attribute.ErrorMessage, new[] { property.Name }));
                    }
                }
            }

            return(null);
        }
Example #2
0
        public override IEnumerable <ModelValidationResult> Validate(object container)
        {
            // NOTE: Container is never used here, because IValidatableObject doesn't give you
            // any way to get access to your container.

            object model = Metadata.Model;

            if (model == null)
            {
                return(Enumerable.Empty <ModelValidationResult>());
            }

            IValidatableObject validatable = model as IValidatableObject;

            if (validatable == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              "The model object inside the metadata claimed to be compatible with {0}, but was actually {1}.",
                              typeof(IValidatableObject).FullName,
                              model.GetType().FullName
                              )
                          );
            }

            ValidationContext validationContext = new ValidationContext(validatable, null, null)
            {
                DisplayName = Metadata.DisplayName,
                MemberName  = Metadata.PropertyName
            };

            return(ConvertResults(validatable.Validate(validationContext)));
        }
        public override IEnumerable <ModelValidationResult> Validate(object container)
        {
            // NOTE: Container is never used here, because IValidatableObject doesn't give you
            // any way to get access to your container.

            object model = Metadata.Model;

            if (model == null)
            {
                return(Enumerable.Empty <ModelValidationResult>());
            }

            IValidatableObject validatable = model as IValidatableObject;

            if (validatable == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              MvcResources.ValidatableObjectAdapter_IncompatibleType,
                              typeof(IValidatableObject).FullName,
                              model.GetType().FullName));
            }

            ValidationContext validationContext = new ValidationContext(validatable, null, null);

            return(ConvertResults(validatable.Validate(validationContext)));
        }
        public static void ForceValidation(ModelStateDictionary stateDictionary, Object m)
        {
            IValidatableObject model = null;

            if (m is IValidatableObject)
            {
                model = m as IValidatableObject;

                IEnumerable <ValidationResult> errors = model.Validate(new ValidationContext(model, null, null));

                List <string>     modelStateKeys   = stateDictionary.Keys.ToList();
                List <ModelState> modelStateValues = stateDictionary.Values.ToList();

                foreach (ValidationResult error in errors)
                {
                    List <string> errorMemberNames = error.MemberNames.ToList();
                    if (errorMemberNames.Count == 0)
                    {
                        errorMemberNames.Add(String.Empty);
                    }

                    foreach (string memberName in errorMemberNames)
                    {
                        int index = modelStateKeys.IndexOf(memberName);
                        if (index < 0 || !modelStateValues[index].Errors.Any(i => i.ErrorMessage == error.ErrorMessage))
                        {
                            stateDictionary.AddModelError(memberName, error.ErrorMessage);
                        }
                    }
                }
            }
        }
Example #5
0
        public override IEnumerable <ModelValidationResult> Validate(
            ModelMetadata metadata,
            object container
            )
        {
            // NOTE: Container is never used here, because IValidatableObject doesn't give you
            // any way to get access to your container.

            object model = metadata.Model;

            if (model == null)
            {
                return(Enumerable.Empty <ModelValidationResult>());
            }

            IValidatableObject validatable = model as IValidatableObject;

            if (validatable == null)
            {
                throw Error.InvalidOperation(
                          SRResources.ValidatableObjectAdapter_IncompatibleType,
                          model.GetType()
                          );
            }

            ValidationContext validationContext = new ValidationContext(validatable, null, null);

            return(ConvertResults(validatable.Validate(validationContext)));
        }
Example #6
0
        public ObjectValidationResult ValidateObject(IValidatableObject validatableObject)
        {
            if (validatableObject == null)
            {
                return(new ObjectValidationResult
                {
                    Message = "Object can not be null."
                });
            }

            var validationResults =
                validatableObject.Validate(new ValidationContext(this));

            var enumerable =
                validationResults as IList <ValidationResult> ?? validationResults.ToList();

            if (enumerable.Any())
            {
                return(new ObjectValidationResult
                {
                    Message = enumerable.First().ErrorMessage
                });
            }

            return(new ObjectValidationResult
            {
                Success = true
            });
        }
    /// <summary>
    /// Validates a column of an IValidatableObject for use with IDataErrorInfo.
    /// </summary>
    /// <param name="instance"></param>
    /// <param name="memberName"></param>
    /// <returns>Validation error, or empty when valid.</returns>
    public static string Validate(this IValidatableObject instance, string memberName)
    {
        var errors = instance.Validate(null)
                     .Where(vr => vr.MemberNames.Contains(memberName))
                     .ToList();

        return(ValidateInner(errors));
    }
        public static List <ValidationResult> GetValidationErrors(IValidatableObject obj)
        {
            var result            = new List <ValidationResult>();
            var validationContext = new ValidationContext(obj);

            Validator.TryValidateObject(obj, validationContext, result);
            obj.Validate(validationContext);

            return(result);
        }
 public bool modelStateIsValidAfterReRunValidationOnComplexAttributes(
     ModelStateDictionary modelState, IValidatableObject model)
 {
     modelState.Clear();
     var errors = model.Validate(new ValidationContext(model, null, null));
     foreach(var error in errors)
         foreach(var memberName in error.MemberNames)
             modelState.AddModelError(memberName, error.ErrorMessage);
     return modelState.IsValid;
 }
    /// <summary>
    /// Validates this instance, and throws an exception when validation fails.
    /// </summary>
    /// <typeparam name="TException">The type of the exception.</typeparam>
    /// <param name="instance">The instance.</param>
    public static void Validate <TException>(this IValidatableObject instance)
        where TException : Exception
    {
        var validationErrorMessage = instance.Validate();

        if (!string.IsNullOrEmpty(validationErrorMessage))
        {
            throw (Exception)Activator.CreateInstance(typeof(TException), validationErrorMessage);
        }
    }
Example #11
0
        public static string RaiseValidationAndGetResult(this IValidatableObject validatableObject, ValidationContext context)
        {
            string result           = null;
            var    validationResult = validatableObject.Validate(context);

            if (validationResult.Any())
            {
                result = string.Join(Environment.NewLine, validationResult.Select(x => x.ErrorMessage));
            }
            return(result);
        }
Example #12
0
        public static void RunCustomValidation(this ModelStateDictionary modelState, IValidatableObject viewModel)
        {
            var errors = viewModel.Validate(new ValidationContext(viewModel, null, null));

            foreach (var error in errors)
            {
                foreach (var memberName in error.MemberNames)
                {
                    modelState.AddModelError(memberName, error.ErrorMessage);
                }
            }
        }
Example #13
0
        public virtual IReadOnlyList <ValidationResult> Validate(object validatingObject)
        {
            var validationErrors = new List <ValidationResult>();

            if (validatingObject is IValidatableObject)
            {
                IValidatableObject o = validatingObject as IValidatableObject;
                validationErrors.AddRange(o.Validate(new ValidationContext(o)));
            }

            return(validationErrors);
        }
Example #14
0
        public static bool IsValidField(this ModelStateDictionary modelSate, string key, IValidatableObject validatableObject)
        {
            if (!modelSate.IsValidField(key)) return false;

            var validationResults = validatableObject.Validate(new ValidationContext(validatableObject, null, null));
            foreach (var validationResult in validationResults)
                if (validationResult.MemberNames.Contains(key))
                {
                    modelSate.AddModelError(key, validationResult.ErrorMessage);
                    return false;
                }
            return true;
        }
 public static ModelStateDictionary MergeWithValidatableObject(this ModelStateDictionary modelState, IValidatableObject obj)
 {
     IEnumerable<ValidationResult> errors = obj.Validate(new ValidationContext(obj, null, null));
     foreach (ValidationResult error in errors)
         foreach (string memberName in error.MemberNames)
         {
             if (modelState.ContainsKey(memberName))
                 modelState.AddModelError(memberName, error.ErrorMessage);
             else
                 modelState.AddModelError(memberName, error.ErrorMessage);
         }
     return modelState;
 }
Example #16
0
        public static void IsValid(this IValidatableObject obj)
        {
            if (obj == null)
            {
                return;
            }

            var result = obj.Validate(null);

            if (result.Any())
            {
                throw new ApplicationException(result.First().ErrorMessage);
            }
        }
Example #17
0
        /// <summary>
        /// Internal iterator to enumerate all validation errors for the given object instance.
        /// </summary>
        /// <param name="instance">Object instance to test.</param>
        /// <param name="validationContext">Describes the object type.</param>
        /// <param name="validateAllProperties">if <c>true</c> also validates all properties.</param>
        /// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param>
        /// <returns>A collection of validation errors that result from validating the <paramref name="instance"/> with
        /// the given <paramref name="validationContext"/>.</returns>
        /// <exception cref="ArgumentNullException">When <paramref name="instance"/> is null.</exception>
        /// <exception cref="ArgumentNullException">When <paramref name="validationContext"/> is null.</exception>
        /// <exception cref="ArgumentException">When <paramref name="instance"/> doesn't match the
        /// <see cref="ValidationContext.ObjectInstance"/> on <paramref name="validationContext"/>.</exception>
        private static IEnumerable <ValidationError> GetObjectValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            if (validationContext == null)
            {
                throw new ArgumentNullException("validationContext");
            }

            // Step 1: Validate the object properties' validation attributes
            List <ValidationError> errors = new List <ValidationError>();

            errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError));

            // We only proceed to Step 2 if there are no errors
            if (errors.Any())
            {
                return(errors);
            }

            // Step 2: Validate the object's validation attributes
            IEnumerable <ValidationAttribute> attributes = _store.GetTypeValidationAttributes(validationContext);

            errors.AddRange(GetValidationErrors(instance, validationContext, attributes, breakOnFirstError));

#if !SILVERLIGHT
            // We only proceed to Step 3 if there are no errors
            if (errors.Any())
            {
                return(errors);
            }

            // Step 3: Test for IValidatableObject implementation
            IValidatableObject validatable = instance as IValidatableObject;
            if (validatable != null)
            {
                IEnumerable <ValidationResult> results = validatable.Validate(validationContext);

                foreach (ValidationResult result in results.Where(r => r != ValidationResult.Success))
                {
                    errors.Add(new ValidationError(null, instance, result));
                }
            }
#endif

            return(errors);
        }
        public void TestValidate()
        {
            //arrange
            var rule = new IsNotNullOrEmptyRule <string>("Value cannot be null");

            _validatableObject.Value = "Hello World";
            _validatableObject.AddValidationRule(rule);

            //act
            var actual = _validatableObject.Validate();

            //assert
            Assert.AreEqual(true, actual);
        }
Example #19
0
        // *******************************************************************

        /// <summary>
        /// This method validates the current object and returns the result
        /// of any failing validations.
        /// </summary>
        /// <returns>A list of failing validations.</returns>
        /// <exception cref="ArgumentException">This exception is thrown whenever
        /// the argument is missing, or null.</exception>
        public static IEnumerable <ValidationResult> Validate(
            this IValidatableObject validatableObject
            )
        {
            // Validate the parameters before attempting to use them.
            Guard.Instance().ThrowIfNull(validatableObject, nameof(validatableObject));

            // Validate ourselves.
            var results = validatableObject.Validate(
                new ValidationContext(validatableObject)
                );

            // Return the results.
            return(results);
        }
        public static bool IsValid(this IValidatableObject obj, ValidationContext context = null)
        {
            if (obj == null)
            {
                return(false);
            }

            if (context == null)
            {
                context = new ValidationContext(obj);
            }

            var result = obj.Validate(context);

            return(!result.Any());
        }
Example #21
0
        /// <summary>
        /// Evaluates the condition.
        /// </summary>
        /// <returns></returns>
        protected override bool EvaluateIsValid()
        {
            if (_validatorCollection == null)
            {
                _validatorCollection = new PageValidatorCollection(Page);
            }

            ICollection <ModelPropertyValidator> validators = GetPropertyValidators();

            if (validators.Count > 0)
            {
                Type modelType           = GetModelType();
                IValidatableObject model = Activator.CreateInstance(modelType) as IValidatableObject;

                if (model != null)
                {
                    // set the model with the form values
                    List <ValidationResult> results = new List <ValidationResult>();
                    foreach (ModelPropertyValidator propertyValidator in validators)
                    {
                        PropertyInfo property = modelType.GetProperty(propertyValidator.PropertyName);
                        object       propertyValue;
                        try
                        {
                            propertyValue = GetModelPropertyValue(property.Name, propertyValidator.ControlToValidate);
                        }
                        catch (ValidationException ex)
                        {
                            results.Add(ex.ValidationResult);
                            continue;
                        }
                        property.SetValue(model, propertyValue, null);
                    }

                    results.AddRange(model.Validate(new ValidationContext(model, null, null)));
                    foreach (ValidationResult result in results)
                    {
                        _validatorCollection.Add(new ValidationError(result.ErrorMessage, ValidationGroup));
                    }

                    return(!results.Any());
                }
            }

            return(true);
        }
Example #22
0

        
        private static void ValidValidatableObject(object model, Type modelType, ModelValid modelValid, string modelName)
        {
            IValidatableObject validatableObject = model as IValidatableObject;

            if (validatableObject == null)
            {
                return;
            }

            ValidationContext validationContext = new ValidationContext(model);

            foreach (var validResult in validatableObject.Validate(validationContext))
            {
                modelValid.ValidResults.Add(new ValidFailure()
                {
                    ErrorMessage = validResult.ErrorMessage,
                    MemberNames  = validResult.MemberNames,
                    Name         = modelName
                });
            }
        }
Example #24
0
            private void ValidateBindings(IValidatableObject subject, ValidationContext context)
            {
                if (subject is null)
                {
                    return;
                }

                var errors = subject.Validate(context).ToList();

                var bindingsOfSameSubject = this.bindings.Where(x => this.GetBindingDataSource(x.DataSource) == subject);

                foreach (var binding in bindingsOfSameSubject)
                {
                    var boundProperty = binding.BindingMemberInfo.BindingMember;

                    var errorMessage = errors
                                       .FirstOrDefault(x => x.MemberNames.Contains(boundProperty))
                                       ?.ErrorMessage;

                    this.ErrorProvider?.SetError(binding.Control, errorMessage);
                }
            }
Example #25
0
        public static bool IsValid(this IValidatableObject input, out string error)
        {
            EnsureArg.IsNotNull(input, nameof(input));

            var builder          = new StringBuilder();
            var validationErrors = input.Validate(new ValidationContext(input));

            if (!validationErrors.Any())
            {
                error = null;
                return(true);
            }

            builder.Append("Validation errors: ");
            foreach (var validationError in validationErrors)
            {
                builder.AppendLine($"{validationError.ErrorMessage}");
            }

            error = builder.ToString();
            return(false);
        }
Example #26
0
        // *******************************************************************

        /// <summary>
        /// This method validates the current object and throws an exception
        /// with the contents of any failing validations.
        /// </summary>
        /// <exception cref="ArgumentException">This exception is thrown whenever
        /// the argument is missing, or null.</exception>
        /// <exception cref="ValidationException">This exception is thrown if
        /// any of the validation checks fail.</exception>
        public static void ThrowIfInvalid(
            this IValidatableObject validatableObject
            )
        {
            // Validate the parameters before attempting to use them.
            Guard.Instance().ThrowIfNull(validatableObject, nameof(validatableObject));

            // Validate ourselves.
            var results = validatableObject.Validate(
                new ValidationContext(validatableObject)
                );

            // Did anything fail?
            if (results.Any())
            {
                // Format the invalid member names.
                var memberNames = string.Join(
                    ",",
                    results.Select(x => string.Join(",", x.MemberNames))
                    );

                // Format the error message.
                var errorMessages = string.Join(
                    ",",
                    results.Select(x => x.ErrorMessage)
                    );

                // Throw the exception.
                throw new ValidationException(
                          message: string.Format(
                              Resources.VerifiableObject_Invalid,
                              validatableObject.GetType().Name,
                              errorMessages,
                              memberNames
                              )
                          );
            }
        }
Example #27
0
        //public override IEnumerable<ModelValidationResult> Validate(object container)
        //{
        //    object model = base.Metadata.Model;

        //    if(model != null)
        //    {
        //        // Ask StructureMap to do setter injection for all properties decorated with SetterProperty attribute.
        //        _container.BuildUp(model);
        //    }

        //    return base.Validate(container);
        //}

        public override IEnumerable <ModelValidationResult> Validate(object container)
        {
            object model = base.Metadata.Model;

            if (model != null)
            {
                IValidatableObject instance = model as IValidatableObject;
                if (instance == null)
                {
                    //the base implementation will throw an exception after
                    //doing the same check - so let's retain that behaviour
                    return(base.Validate(container));
                }
                /* replacement for the core functionality */
                ValidationContext validationContext = CreateValidationContext(instance);
                return(this.ConvertResults(instance.Validate(validationContext)));
            }
            else
            {
                return(base.Validate(container));  /*base returns an empty set
                                                    * of values for null. */
            }
        }
Example #28
0

        
        public static void EnsureIsValid(this IValidatableObject obj, ValidationContext context = null)
        {
            if (obj == null)
            {
                return;
            }

            if (context == null)
            {
                context = new ValidationContext(obj);
            }

            var result = obj.Validate(context);

            var validationResults = result as ValidationResult[] ?? result.ToArray();

            if (validationResults.Any())
            {
                var errors = from e in validationResults
                             select new ErrorMessage(e.ErrorMessage, string.Join(",", e.MemberNames));

                throw  new BusinessException(errors.ToList());
            }
        }
Example #30
0

        
Example #31
0
        public virtual IEnumerable <DbValidationError> Validate(
            EntityValidationContext entityValidationContext,
            InternalMemberEntry property)
        {
            if (property != null && property.CurrentValue == null)
            {
                return(Enumerable.Empty <DbValidationError>());
            }
            ValidationContext validationContext = entityValidationContext.ExternalValidationContext;

            validationContext.SetDisplayName(property, this._displayAttribute);
            IValidatableObject             validatableObject = property == null ? (IValidatableObject)entityValidationContext.InternalEntity.Entity : (IValidatableObject)property.CurrentValue;
            IEnumerable <ValidationResult> validationResults;

            try
            {
                validationResults = validatableObject.Validate(validationContext);
            }
            catch (Exception ex)
            {
                throw new DbUnexpectedValidationException(Strings.DbUnexpectedValidationException_IValidatableObject((object)validationContext.DisplayName, (object)ObjectContextTypeCache.GetObjectType(validatableObject.GetType())), ex);
            }
            return(DbHelpers.SplitValidationResults(validationContext.MemberName, validationResults ?? Enumerable.Empty <ValidationResult>()));
        }
        public GlogErrorsResult(IValidatableObject validatable)
        {
            var validationResults = validatable.Validate(new ValidationContext(validatable));

            errors = validationResults.Select(vr => vr.ErrorMessage).ToList();
        }
Example #33
0
        public async Task <IActionResult> OnPost()
        {
            // Remove all errors from required fields that are not in the Form
            foreach (var key in ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0 && !this.Request.Form.Keys.Any(ek => ek == k)))
            {
                ModelState[key].Errors.Clear();
                ModelState[key].ValidationState = ModelValidationState.Valid;
            }



            // Test for IValidatableObject implementation
            IValidatableObject validatable = this.EngineView;

            var validationContext = new ValidationContext(this.EngineView, this.HttpContext.RequestServices, null);
            var results           = validatable.Validate(validationContext);

            foreach (ValidationResult result in results.Where(r => r != ValidationResult.Success))
            {
                ModelState.AddModelError("", result.ErrorMessage);
            }


            if (!ModelState.IsValid)
            {
                return(Page());
            }

            try
            {
                YEngine engine;

                // Merge engine from repository with the one we are editing here
                if (!this.EngineView.IsNew)
                {
                    var engineGetAction = await this.enginesController.GetEngineAsync(this.EngineView.Engine.Id).ConfigureAwait(false);

                    if (engineGetAction.HasError)
                    {
                        throw new Exception(engineGetAction.Error?.ToString());
                    }

                    engine            = engineGetAction.Value;
                    engine.EngineName = this.EngineView.EngineName;
                    engine.EngineType = this.EngineView.EngineType;
                    engine.Owners     = this.EngineView.Engine.Owners;
                    engine.Members    = this.EngineView.Engine.Members;
                    engine.Comments   = this.EngineView.Comments;
                }
                else
                {
                    engine = this.EngineView.Engine;
                }

                var saveEngineAction = await this.enginesController.SaveEngineAsync(engine.Id, engine);

                if (saveEngineAction.HasError)
                {
                    throw new Exception(saveEngineAction.Error?.ToString());
                }

                return(Redirect("/Engines/Index"));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return(Page());
            }
        }
Example #34
-1
		public ObjectValidationResult ValidateObject(IValidatableObject validatableObject)
		{
			if (validatableObject == null)
			{
				return new ObjectValidationResult
				{
					Message = "Object can not be null."
				};
			}

			var validationResults =
				validatableObject.Validate(new ValidationContext(this));

			var enumerable =
				validationResults as IList<ValidationResult> ?? validationResults.ToList();

			if (enumerable.Any())
			{
				return new ObjectValidationResult
				{
					Message = enumerable.First().ErrorMessage
				};
			}

			return new ObjectValidationResult
			{
				Success = true
			};
		}