Example #1
0
        public void Validate_can_validate_all_attributes()
        {
            // Arrange
            var model = new ClassWithMultiValidationAttributes
            {
                Company = "My Company Name"
            };

            // Action
            var metaData = new ModelMetadata(ModelMetadataProviders.Current,
                                             null,
                                             () => model,
                                             typeof(ClassWithMultiValidationAttributes),
                                             null);


            var validator = ModelValidator.GetModelValidator(metaData);
            var result    = validator.Validate(model).ToList();

            // Assert
            Assert.AreEqual(2, result.Count());
            Assert.AreEqual("The Name field is required.", result[0].Message);
            Assert.AreEqual("ClassWithMultiValidationAttributes.Name", result[0].MemberName);
            Assert.AreEqual("The field Company must be a string with a maximum length of 6.", result[1].Message);
            Assert.AreEqual("ClassWithMultiValidationAttributes.Company", result[1].MemberName);
        }
Example #2
0
        /// <summary>
        /// Binds the model, and honours any validation attributes set on dyanmically inserted form elements, by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
        /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
        /// <returns>
        /// The bound object.
        /// </returns>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="bindingContext "/>parameter is null.</exception>
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
            {
                return(bindingContext.Model);
            }

            var model = base.BindModel(controllerContext, bindingContext);

            var adminViewModel = model as AdminViewModel;

            if (adminViewModel == null)
            {
                return(model);
            }

            var criteriaValue = bindingContext.ValueProvider.GetValue(ValidationPropertyName);

            adminViewModel.CriteriaModel.Criteria = criteriaValue != null ? criteriaValue.AttemptedValue : string.Empty;

            ModelMetadata  modelMetadata      = ModelMetadataProviders.Current.GetMetadataForType(() => adminViewModel.CriteriaModel, typeof(ICriteriaModel));
            ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controllerContext);

            foreach (ModelValidationResult result in compositeValidator.Validate(null))
            {
                bindingContext.ModelState.AddModelError(ValidationPropertyName, result.Message);
            }

            return(model);
        }
Example #3
0
        /// <summary>
        /// 验证实例 model 数据
        /// </summary>
        /// <typeparam name="T">实例的类型</typeparam>
        /// <param name="model">实例</param>
        /// <param name="validationResult">错误信息</param>
        /// <returns>验证通过 true 不通过 false</returns>
        public static bool Validate <T>(T model, out List <ModelValidationResult> validationResult)
        {
            var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(T));

            validationResult = ModelValidator.GetModelValidator(modelMetadata, new ControllerContext()).Validate(null).ToList();
            return(validationResult.Count == 0);
        }
        public void GetModelValidatorWithFailedPropertyValidatorsPreventsTypeValidatorFromRunning()
        {
            // Arrange
            ControllerContext context = new ControllerContext();
            DataErrorInfo1    model   = new DataErrorInfo1 {
                Error = "Some Type Error"
            };

            model["SomeStringProperty"]      = "Some Property Error";
            model["SomeOtherStringProperty"] = "Some Other Property Error";
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(
                () => model,
                model.GetType()
                );
            ModelValidator validator = ModelValidator.GetModelValidator(metadata, context);

            // Act
            List <ModelValidationResult> result = validator.Validate(null).ToList();

            // Assert
            Assert.Equal(2, result.Count);
            Assert.Equal("SomeStringProperty", result[0].MemberName);
            Assert.Equal("Some Property Error", result[0].Message);
            Assert.Equal("SomeOtherStringProperty", result[1].MemberName);
            Assert.Equal("Some Other Property Error", result[1].Message);
        }
Example #5
0
        public void Validate_can_validate_nested_item_in_list()
        {
            // Arrange
            var model = new ParentClass
            {
                Children = new List <NestedClass>
                {
                    new NestedClass
                    {
                        Name = "Van Thoai Nguyen"
                    }
                }
            };

            // Action
            var metaData = new ModelMetadata(ModelMetadataProviders.Current,
                                             null,
                                             () => model,
                                             typeof(ParentClass),
                                             null);


            var validator = ModelValidator.GetModelValidator(metaData);
            var result    = validator.Validate(model).ToList();

            // Assert
            Assert.AreEqual(1, result.Count());
            Assert.AreEqual("The field Name must be a string with a maximum length of 5.", result[0].Message);
            Assert.AreEqual("ParentClass.Children[0].Name", result[0].MemberName);
        }
        public IEnumerable <ModelValidationResult> ValidateModel(Type modelType, object modelValue, ControllerContext controllerContext)
        {
            var modelMetadata = ModelMetadataProvider.GetMetadataForType(() => modelValue, modelType);
            var validator     = ModelValidator.GetModelValidator(modelMetadata, controllerContext);

            return(validator.Validate(null));
        }
Example #7
0
        public void GetModelValidator_DoesNotReadPropertyValues()
        {
            ModelValidatorProvider[] originalProviders = ModelValidatorProviders.Providers.ToArray();
            try
            {
                // Arrange
                ModelValidatorProviders.Providers.Clear();
                ModelValidatorProviders.Providers.Add(new ObservableModelValidatorProvider());

                ObservableModel   model             = new ObservableModel();
                ModelMetadata     metadata          = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(ObservableModel));
                ControllerContext controllerContext = new ControllerContext();

                // Act
                ModelValidator          validator = ModelValidator.GetModelValidator(metadata, controllerContext);
                ModelValidationResult[] results   = validator.Validate(model).ToArray();

                // Assert
                Assert.False(model.PropertyWasRead());
            }
            finally
            {
                ModelValidatorProviders.Providers.Clear();
                foreach (ModelValidatorProvider provider in originalProviders)
                {
                    ModelValidatorProviders.Providers.Add(provider);
                }
            }
        }
 private static ModelValidator GetModelValidator(this object model, ControllerBase controller)
 {
     return(ModelValidator.GetModelValidator(
                ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
                controller.ControllerContext
                ));
 }
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object        model    = bindingContext.ModelMetadata.Model = base.BindModel(controllerContext, bindingContext);
            ModelMetadata metadata = bindingContext.ModelMetadata;

            if (metadata.IsComplexType || null == model)
            {
                return(model);
            }

            //针对简单类型的Model验证
            Dictionary <string, bool> dictionary = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (ModelValidationResult result in ModelValidator.GetModelValidator(metadata, controllerContext).Validate(null))
            {
                string key = bindingContext.ModelName;
                if (!dictionary.ContainsKey(key))
                {
                    dictionary[key] = bindingContext.ModelState.IsValidField(key);
                }
                if (dictionary[key])
                {
                    bindingContext.ModelState.AddModelError(key, result.Message);
                }
            }
            return(model);
        }
Example #10
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object model = null;

            try
            {
                var strJson = controllerContext.HttpContext.Request.Params[bindingContext.ModelName];
                if (string.IsNullOrEmpty(strJson))
                {
                    return(null);
                }
                model = JsonConvert.DeserializeObject(strJson, bindingContext.ModelType);
                var modelMetaData = ModelMetadataProviders.Current
                                    .GetMetadataForType(() => model, bindingContext.ModelType);
                var validator = ModelValidator
                                .GetModelValidator(modelMetaData, controllerContext);
                var validationResult = validator.Validate(null);
                foreach (var item in validationResult)
                {
                    bindingContext.ModelState
                    .AddModelError(item.MemberName, item.Message);
                }
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelType.Name, ex.Message);
            }
            return(model);
        }
Example #11
0
        /// <summary>
        /// The method is copied from base class (base.OnModelUpdated(controllerContext, bindingContext))
        /// and modified. Modified region is commented in the method source code.
        /// </summary>
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var startedValid = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null))
            {
                // START added code

                var propertyMetadata = bindingContext.PropertyMetadata[validationResult.MemberName];
                var customAttributes = bindingContext.ModelType.GetProperty(propertyMetadata.PropertyName)
                                       .GetCustomAttributes(typeof(SkipValidationIfAttribute), true)
                                       .Cast <SkipValidationIfAttribute>();

                if (customAttributes.Any(a => a.ShouldSkipValidation(controllerContext, bindingContext, propertyMetadata, validationResult)))
                {
                    continue;
                }

                // END added code

                string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);

                if (!startedValid.ContainsKey(subPropertyName))
                {
                    startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
                }

                if (startedValid[subPropertyName])
                {
                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
                }
            }
        }
Example #12
0
    private static IEnumerable <ModelValidationResult> GetModelValidationResults <T>(T model)
    {
        var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(T));
        /* build a stub controller context */
        var controllerContext = Fake.ControllerContext.Build();
        var validator         = ModelValidator.GetModelValidator(modelMetadata, controllerContext);

        return(validator.Validate(null));
    }
        public override object BindModel(ControllerContext controllerContext,
                                         ModelBindingContext bindingContext)
        {
            TEntity entity = base.BindModel(controllerContext, bindingContext) as TEntity;

            _repositoryFactory = DependencyResolverProxy.Resolver.GetService <IRepositoryFactory>();

            foreach (var property in entity.GetEnumerableProperties())
            {
                Type[] collectionTypes = property.PropertyType.GetGenericArguments();
                if (collectionTypes.Length > 0)
                {
                    var providerResult = bindingContext.ValueProvider.GetValue(property.Name);
                    if (providerResult != null)
                    {
                        string[] ids = providerResult.RawValue as string[];
                        if (ids != null)
                        {
                            var targetType          = property.PropertyType.GetGenericArguments()[0];
                            var repositoryGetMethod = _repositoryFactory.GetType().GetMethod("Get");
                            var genericGetMethod    = repositoryGetMethod.MakeGenericMethod(targetType);
                            var repository          = genericGetMethod.Invoke(_repositoryFactory, null);
                            var collection          = property.GetValue(entity, null);

                            var find = repository.GetType().GetMethods().Where(m => m.Name.Equals("Find") &&
                                                                               m.ReturnType == targetType).Single();

                            var add = collection.GetType().GetMethod("Add");

                            foreach (var idString in ids)
                            {
                                int id;
                                if (int.TryParse(idString, out id))
                                {
                                    var collectionInstance = find.Invoke(repository,
                                                                         new object[] { new object[] { id } });

                                    var collectionEntity = add.Invoke(collection,
                                                                      new object[] { collectionInstance });
                                }
                            }
                        }
                    }
                }
            }

            bindingContext.ModelState.Clear();
            var metaData  = ModelMetadataProviders.Current.GetMetadataForType(() => entity, typeof(TEntity));
            var validator = ModelValidator.GetModelValidator(metaData, controllerContext);

            validator.Validate(null).ToList().ForEach(result =>
            {
                bindingContext.ModelState.AddModelError(result.MemberName, result.Message);
            });

            return(entity);
        }
 protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) {
     foreach (var validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null)) {
         string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);
         if (bindingContext.PropertyFilter(subPropertyName)) {
             if (bindingContext.ModelState.IsValidField(subPropertyName)) {
                 bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
             }
         }
     }
 }
Example #15
0
        public void Validate_on_basic_types()
        {
            // Arrange
            var           model    = "Thoai";
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());

            var validator = ModelValidator.GetModelValidator(metadata);

            // Action
            var result = validator.Validate(model);


            // Assert
            Assert.AreEqual(0, result.Count());
        }
Example #16
0
        public static void Revalidate(this Controller controller, object model)
        {
            var modelState = controller.ModelState;

            if (!modelState.IsValid)
            {
                modelState.Clear();
                ModelMetadata  modelMetadata      = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
                ModelValidator compositeValidator = ModelValidator.GetModelValidator(modelMetadata, controller.ControllerContext);

                foreach (ModelValidationResult result in compositeValidator.Validate(null))
                {
                    modelState.AddModelError(result.MemberName, result.Message);
                }
            }
        }
Example #17
0
        protected bool TryValidateModel(object model, string prefix)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());

            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, this.ViewContext).Validate(null))
            {
                this.ModelState.AddModelError(CreateSubPropertyName(prefix, validationResult.MemberName), validationResult.Message);
            }

            return(this.ModelState.IsValid);
        }
Example #18
0
        /// <summary>
        /// Revalidates the model passed as the first parameter.
        /// </summary>
        /// <param name="model">The model instance you wish to validate.</param>
        /// <returns></returns>
        protected internal bool TryValidateModel(object model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            System.Web.ModelBinding.ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            var t = new ModelBindingExecutionContext(new HttpContextWrapper(HttpContext.Current), new System.Web.ModelBinding.ModelStateDictionary());

            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, t).Validate(null))
            {
                ModelState.AddModelError(validationResult.MemberName, validationResult.Message);
            }

            return ModelState.IsValid;
        }
Example #19
0
        public void GetModelValidatorWithPropertyLevelValidator()
        {
            // Arrange
            ControllerContext context = new ControllerContext();
            DataErrorInfo1    model   = new DataErrorInfo1();

            model["SomeStringProperty"] = "Some Property Error";
            ModelMetadata  metadata  = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            ModelValidator validator = ModelValidator.GetModelValidator(metadata, context);

            // Act
            ModelValidationResult result = validator.Validate(null).Single();

            // Assert
            Assert.Equal("SomeStringProperty", result.MemberName);
            Assert.Equal("Some Property Error", result.Message);
        }
Example #20
0
        public void Test_complex_validation()
        {
            // Arrange
            var order = new Order
            {
                OrderId          = 1,
                FirstOrderDetail = new OrderDetail
                {
                    OrderId     = 1,
                    Price       = 100,
                    ProductName = "P123456"
                },
                Details = new List <OrderDetail>
                {
                    new OrderDetail
                    {
                        OrderId     = 1,
                        Price       = 100,
                        ProductName = "P123456"
                    },
                    new OrderDetail
                    {
                        OrderId     = 1,
                        Price       = 200,
                        ProductName = "P2"
                    }
                }
            };
            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => order, order.GetType());


            // Action
            var validator         = ModelValidator.GetModelValidator(metadata);
            var validationResults = validator.Validate(null).ToList();

            // Assert
            Assert.AreEqual(2, validationResults.Count());
            Assert.AreEqual("Order.Details[0].ProductName", validationResults[0].MemberName);
            Assert.AreEqual("The field ProductName must be a string with a maximum length of 5.", validationResults[0].Message);

            Assert.AreEqual("Order.FirstOrderDetail.ProductName", validationResults[1].MemberName);
            Assert.AreEqual("The field ProductName must be a string with a maximum length of 5.", validationResults[1].Message);
        }
Example #21
0
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var startedValid = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (var validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null))
            {
                var subPropertyName = CreateSubPropertyName(bindingContext.ModelType.Name, validationResult.MemberName);

                if (!startedValid.ContainsKey(subPropertyName))
                {
                    startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
                }

                if (startedValid[subPropertyName])
                {
                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
                }
            }
        }
Example #22
0
        protected internal bool TryValidateModel(object model, string prefix, out string _modelError)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());                                                   //using System.Web.ModelBinding;
            var           t        = new ModelBindingExecutionContext(new HttpContextWrapper(HttpContext.Current), new System.Web.ModelBinding.ModelStateDictionary()); //using System.Web;

            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, t).Validate(null))
            {
                ModelState.AddModelError(validationResult.MemberName, validationResult.Message);
            }

            _modelError = string.Join(" | ", ModelState.Values
                                      .SelectMany(v => v.Errors)
                                      .Select(e => e.ErrorMessage));
            return(ModelState.IsValid);
        }
Example #23
0
        public void Validate_can_validate_on_null_but_required_complex_property()
        {
            // Arrange
            var model = new ParentClassWithARequiredProperty();

            // Action
            var metaData = new ModelMetadata(ModelMetadataProviders.Current,
                                             null,
                                             () => model,
                                             typeof(ParentClassWithARequiredProperty),
                                             null);


            var validator = ModelValidator.GetModelValidator(metaData);
            var result    = validator.Validate(model).ToList();

            // Assert
            Assert.AreEqual(1, result.Count());
            Assert.AreEqual("The IamRequired field is required.", result[0].Message);
            Assert.AreEqual("ParentClassWithARequiredProperty.IamRequired", result[0].MemberName);
        }
        protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //base.OnModelUpdated(controllerContext, bindingContext);

            //start reflected code
            Dictionary <string, bool> dictionary = new Dictionary <string, bool>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase);

            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate((object)null))
            {
                string subPropertyName = DefaultModelBinder.CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);
                if (!dictionary.ContainsKey(subPropertyName))
                {
                    dictionary[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);
                }
                if (dictionary[subPropertyName])
                {
                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);
                }
            }
            //end reflected code
        }
Example #25
0
        public void Validate_does_not_validate_require_rule_by_default()
        {
            // Arrange
            var model = new NestedClass
            {
                Name = null
            };

            // Action
            var metaData = new ModelMetadata(ModelMetadataProviders.Current,
                                             null,
                                             () => model,
                                             typeof(NestedClass),
                                             null);


            var validator = ModelValidator.GetModelValidator(metaData);
            var result    = validator.Validate(model).ToList();

            // Assert
            Assert.AreEqual(0, result.Count());
        }
Example #26
0
        protected ModelStateDictionary ValidateModel(object model)
        {
            ControllerContext controllerContext = null;

            if (HttpContext.Current != null)
            {
                var controller = HttpContext.Current.Items["RequestContextController"] as Controller;
                controllerContext = controller.ControllerContext;
            }

            if (controllerContext == null)
            {
                controllerContext = new ControllerContext();
            }

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var method_CreateSubPropertyName = typeof(DefaultModelBinder).GetMethod("CreateSubPropertyName", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            if (method_CreateSubPropertyName == null)
            {
                throw new MissingMethodException(nameof(DefaultModelBinder), "CreateSubPropertyName");
            }

            var metadataForType = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            var modelState      = new ModelStateDictionary();

            foreach (var current in ModelValidator.GetModelValidator(metadataForType, controllerContext).Validate(null))
            {
                var key = method_CreateSubPropertyName.Invoke(null, new object[] { string.Empty, current.MemberName }) as string;
                modelState.AddModelError(key, current.Message);
            }

            return(modelState);
        }
Example #27
0
        public ActionResult Index()
        {
            Address address = new Address
            {
                Province = "江苏",
                City     = "苏州",
                District = "工业园区",
                Street   = "星湖街328号"
            };

            Contact contact = new Contact
            {
                Name         = "张三",
                PhoneNo      = "123456789",
                EmailAddress = "*****@*****.**",
                Address      = address
            };

            ModelMetadata  metadata  = ModelMetadataProviders.Current.GetMetadataForType(() => contact, typeof(Contact));
            ModelValidator validator = ModelValidator.GetModelValidator(metadata, ControllerContext);

            return(View(validator.Validate(contact)));
        }