public static bool IsValid(this IValidatableObject o, out List <ValidationResult> errors)
        {
            ValidationContext ctx = new ValidationContext(o, null, null);

            errors = new List <ValidationResult>();
            return(Validator.TryValidateObject(o, ctx, errors, true));
        }
Ejemplo n.º 2
0
        /// <summary>Wraps up all the validation.</summary>
        public static string CompletelyValidate(IValidatableObject value)
        {
            var passThrough = ObjectValidator.TryValidateFullObject(value);
            var passedTo    = ObjectValidator.GetValidationResults(passThrough);

            return(passedTo);
        }
Ejemplo n.º 3
0
        public static void IsValid(
            [ValidatedNotNull] IValidatableObject validatableArg,
            string argName,
            bool isNullValid = false)
        {
            if (validatableArg is null)
            {
                if (isNullValid)
                {
                    return;
                }

                throw new ArgumentNullException(argName);
            }

            var validationResults = new List <ValidationResult>();
            var isValid           = Validator.TryValidateObject(
                validatableArg,
                new ValidationContext(validatableArg),
                validationResults);

            if (!isValid)
            {
                throw new ArgumentException(
                          $"The input is invalid. Validation errors:{Environment.NewLine}{string.Join(Environment.NewLine, validationResults)}",
                          argName);
            }
        }
Ejemplo n.º 4
0
        //private ObjectValidator()
        //{ }

        /// <summary>Validates an object.</summary>
        /// <param name="value">The object to validate.</param>
        /// <exception cref="ValidationException">The value is invalid.</exception>
        public static void Validate(IValidatableObject value)
        {
            Validator.ValidateObject(value, new ValidationContext(value));

            //No access to instance members
            //_duh = 10;
        }
Ejemplo n.º 5
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)));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// adds notifications to the page due to a isolated form post (multiple forms present)
        /// </summary>
        /// <param name="model"></param>
        public void AddNotifications(IValidatableObject model)
        {
            var notifications            = new List <Notification>();
            var rawExistingNotifications = TempData["Notifications"] as string;

            if (!string.IsNullOrEmpty(rawExistingNotifications))
            {
                var existingNotifications = JsonConvert.DeserializeObject <List <Notification> >(rawExistingNotifications);
                notifications.AddRange(existingNotifications);
            }

            var validationResults = new List <ValidationResult>();

            Validator.TryValidateObject(model, new ValidationContext(model, null, null), validationResults, false);

            foreach (var validationResult in validationResults)
            {
                notifications.Add(new Notification()
                {
                    Message = validationResult.ErrorMessage,
                    Type    = NotificationTypeEnum.Error
                });
            }
            TempData["Notifications"] = JsonConvert.SerializeObject(notifications);
        }
Ejemplo n.º 7
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)));
        }
Ejemplo n.º 8
0
        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);
        }
        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)));
        }
Ejemplo n.º 10
0
        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);
                        }
                    }
                }
            }
        }
Ejemplo n.º 11
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
            });
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Check validity of the data re3cieved from the client, and correctly formats the error reponce if it's not valid
        /// </summary>
        /// <param name="model">The data that was received from the clinet and must b validity checked</param>
        /// <param name="request">HTTPrequest that was recieved, this is used for correct serialisation using content negotiation that has occured</param>
        /// <param name="validateAllProperties">Don't override unless you have a good reason</param>
        /// <returns>Correctly formatted HTTPResponse mesasge with erros if erros have occured, or simply empty responce message with OK status code</returns>
        public static HttpResponseMessage CheckModel(IValidatableObject model, HttpRequestMessage request)
        {
            bool validateAllProperties = true;

            if (model == null)
            {
                return(request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.NoDataRecieved));
            }


            ValidationContext       validationContext = new ValidationContext(model, null, null);
            List <ValidationResult> validationResults = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(model, validationContext, validationResults, validateAllProperties);


            if (!isValid)
            {
                string validatioErrors = string.Empty;
                int    i = 1;

                foreach (var validationErrror in validationResults)
                {
                    validatioErrors += String.Format(" {0}:{1}", i++, validationErrror.ErrorMessage);
                }

                return(request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CreateModelError(validatioErrors)));
            }
            else
            {
                return(request.CreateResponse(HttpStatusCode.OK));
            }
        }
Ejemplo n.º 13
0
        public static IEnumerable <ValidationResult> TryValidateFullObject(IValidatableObject value)
        {
            var    validationResults = new List <ValidationResult>();
            object p = Validator.TryValidateObject(value, new ValidationContext(value), validationResults, true);

            return(validationResults);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// The IsEntityValid.
        /// </summary>
        /// <param name="entity">The entity.<see cref="IValidatableObject"/>.</param>
        /// <returns>The .<see cref="IList{ValidationResult}"/>.</returns>
        public static IList <ValidationResult> IsEntityValid(IValidatableObject entity)
        {
            var context = new ValidationContext(entity);
            IList <ValidationResult> results = new List <ValidationResult>();

            Validator.TryValidateObject(entity, context, results, true);
            return(results);
        }
        /// <summary>
        /// throws BadArgumentException if there is a problem with the token.
        /// </summary>
        /// <param name="request"></param>
#pragma warning disable CA1822
        internal void ValidateRequest(IValidatableObject request)
        {
#pragma warning restore CA1822
            ValidationContext context = new ValidationContext(request, null, null);
            ICollection <ValidationResult> validationResults = new List <ValidationResult>();
            Validator.TryValidateObject(request, context, validationResults, true);
            this.RaiseValidationErrors(validationResults);
        }
    /// <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));
    }
Ejemplo n.º 17
0
        public static bool TryValidate(IValidatableObject value, out IEnumerable <ValidationResult> errors)
        {
            var context = new ValidationContext(value);
            var results = new List <ValidationResult>();

            errors = results;
            return(Validator.TryValidateObject(value, context, results));
        }
Ejemplo n.º 18
0
        public static string RaiseValidationAndGetResult(this IValidatableObject validatableObject, IDictionary <object, object> context)
        {
            string result            = null;
            var    validationContext = new ValidationContext(validatableObject, context);

            result = RaiseValidationAndGetResult(validatableObject, validationContext);
            return(result);
        }
Ejemplo n.º 19
0
        /// <summary>Validates an object.</summary>
        /// <param name="value">The object to validate.</param>
        /// <returns>The list of validation results.</returns>
        public static IEnumerable <ValidationResult> TryValidate(IValidatableObject value)
        {
            var results = new List <ValidationResult>();
            var context = new ValidationContext(value);

            Validator.TryValidateObject(value, context, results, true);
            return(results);
        }
Ejemplo n.º 20
0
        public static IEnumerable <ValidationResult> Validate(this IValidatableObject source)
        {
            var context = new ValidationContext(source);
            var errors  = new Collection <ValidationResult>();
            var results = Validator.TryValidateObject(source, context, errors, true);

            return(errors);
        }
Ejemplo n.º 21
0
        /// <summary>Verifies an argument is not <see langword="null"/> and is valid.</summary>
        /// <typeparam name="T">The type of the argument.</typeparam>
        /// <param name="name">The name of the argument.</param>
        /// <param name="value">The argument value.</param>
        /// <exception cref="ArgumentNullException"><paramref name="value"/> is <see langword="null"/>.</exception>
        /// <exception cref="ValidationException"><paramref name="value"/> is invalid.</exception>
        public static void ArgumentIsValidAndNotNull(string name, IValidatableObject value)
        {
            Verify.ArgumentIsNotNull(name, value);

            var context = new ValidationContext(value);

            Validator.ValidateObject(value, context, true);
        }
Ejemplo n.º 22
0
        /// <summary>
        ///     Validate the given model and add errors
        /// </summary>
        /// <param name="model">The model to be validated</param>
        /// <returns>Return <see cref="BizActionStatus.HasErrors" /></returns>
        protected virtual bool ValidateModelFailed(IValidatableObject model)
        {
            var results = new List <ValidationResult>();

            Validator.TryValidateObject(model, new ValidationContext(model), results);

            AddValidationResults(results);
            return(HasErrors);
        }
Ejemplo n.º 23
0
        public static void EnsureValid(this IValidatableObject input)
        {
            EnsureArg.IsNotNull(input, nameof(input));

            if (!input.IsValid(out string errMessage))
            {
                throw new ValidationException(errMessage);
            }
        }
Ejemplo n.º 24
0
        /// <summary>Attempts to validate an object.</summary>
        /// <param name="value">The object to validate.</param>
        /// <returns>The validation results.</returns>
        public static List <ValidationResult> TryValidate(IValidatableObject value)
        {
            var context = new ValidationContext(value);
            var errors  = new List <ValidationResult>();

            Validator.TryValidateObject(value, context, errors, true);

            return(errors);
        }
        /// <summary>
        /// Validates a validatable object.
        /// </summary>
        /// <param name="validatableObject">
        /// The validatable object.
        /// </param>
        /// <returns>
        /// A list of validation results.
        /// </returns>
        public static List <ValidationResult> Validate(this IValidatableObject validatableObject)
        {
            var validationResult = new List <ValidationResult>();

            System.ComponentModel.DataAnnotations.Validator.TryValidateObject(
                validatableObject, new ValidationContext(validatableObject, null, null), validationResult, true);

            return(validationResult);
        }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        public static List <ValidationResult> GetValidationErrors(this IValidatableObject validatableObject)
        {
            List <ValidationResult> results = new List <ValidationResult>();

            var validationContext = new ValidationContext(validatableObject, null, null);

            Validator.TryValidateObject(validatableObject, validationContext, results, true);

            return(results);
        }
    /// <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);
        }
    }
Ejemplo n.º 29
0
    public bool ValidateDevice(IDeviceDataObject device)
    {
        IValidatableObject v = device as IValidatableObject;

        if (v != null)
        {
            return(device.Validate());
        }
        return(false);
    }
 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;
 }
        public void Add(string key, IValidatableObject viewModel, string message = null)
        {
            _jObject[key] = JObject.FromObject(viewModel);

            if (!string.IsNullOrEmpty(message))
            {
                _messages.Clear();
                _messages.Add(message);
            }
        }
Ejemplo n.º 32
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;
 }
Ejemplo n.º 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
			};
		}