Exemplo n.º 1
0
        private static void AddModelValidation(this ValidationContext validationContext, IValidatableModel model, List <IValidatableModel> handledModels)
        {
            Argument.IsNotNull("validationContext", validationContext);

            if (handledModels.Any(x => ReferenceEquals(x, model)))
            {
                return;
            }

            handledModels.Add(model);

            validationContext.SynchronizeWithContext(model.ValidationContext, true);

            var propertyDataManager = PropertyDataManager.Default;
            var catelTypeInfo       = propertyDataManager.GetCatelTypeInfo(model.GetType());

            foreach (var property in catelTypeInfo.GetCatelProperties())
            {
                var propertyValue = model.GetValue(property.Key);
                var enumerable    = propertyValue as IEnumerable;
                if (enumerable != null && !(propertyValue is string))
                {
                    foreach (var item in enumerable)
                    {
                        var modelItem = item as IValidatableModel;
                        if (modelItem != null)
                        {
                            validationContext.AddModelValidation(modelItem, handledModels);
                        }
                    }
                }

                var propertyModel = propertyValue as IValidatableModel;
                if (propertyModel != null)
                {
                    validationContext.AddModelValidation(propertyModel, handledModels);
                }
            }
        }
        public static ValidationError FirstErrorOnProperty(this IValidatableModel validatable, string propertyName)
        {
            try
            {
                var context = new ValidationContext(validatable)
                {
                    MemberName = propertyName
                };

                var propertyInfo      = validatable.GetType().GetRuntimeProperty(propertyName);
                var value             = propertyInfo.GetValue(validatable);
                var validationResults = new List <ValidationResult>();
                var isValid           = Validator.TryValidateProperty(value, context, validationResults);

                return(validationResults.FirstOrDefault());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception thrown in FirstErrorOnProperty");
                Console.WriteLine(ex);
                return(null);
            }
        }