public void ValidateInvalid() { Booking model = new Booking { ArrivalDate = new DateTime(2011, 6, 4) }; _validator.ModelType = model.GetType().AssemblyQualifiedName; // we need a naming container ContainerControl container = new ContainerControl(); ModelPropertyValidator propertyValidator = new ModelPropertyValidator { ModelType = _validator.ModelType, PropertyName = "ArrivalDate", ControlToValidate = "txtArrivalDate" }; _validatorCollection.Add(propertyValidator); container.Controls.Add(propertyValidator); container.Controls.Add(_validator); _validator.Validate(); Assert.That(_validator.IsValid, Is.False); Assert.That(_validatorCollection.Count, Is.EqualTo(2)); }
/// <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); }