public void Validate(ValidationAttribute attribute, object value, ValidationContext validationContext, bool isValid)
        {
            if (isValid)
            {
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));
            }
            else
            {
                Assert.Throws <ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                Assert.Throws <ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));
            }
            if (!attribute.RequiresValidationContext)
            {
                Assert.Equal(isValid, attribute.IsValid(value));

                // Run the validation twice, in case attributes cache anything
                Assert.Equal(isValid, attribute.IsValid(value));
            }
        }
        public void Validate(ValidationAttribute attribute, object value, ValidationContext validationContext, bool isValid)
        {
            if (isValid)
            {
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                attribute.Validate(value, validationContext);
                Assert.Equal(ValidationResult.Success, attribute.GetValidationResult(value, validationContext));
            }
            else
            {
                Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));

                // Run the validation twice, in case attributes cache anything
                Assert.Throws<ValidationException>(() => attribute.Validate(value, validationContext));
                Assert.NotNull(attribute.GetValidationResult(value, validationContext));
            }
            if (!attribute.RequiresValidationContext)
            {
                Assert.Equal(isValid, attribute.IsValid(value));

                // Run the validation twice, in case attributes cache anything
                Assert.Equal(isValid, attribute.IsValid(value));
            }
        }
        protected void TestAttribute(object value, string expectedExceptionMessage, ValidationAttribute customAttribute = null)
        {
            // Act

            var ex = customAttribute != null
                                ? Assert.Throws <ModelValidationException>(() => customAttribute.Validate(value, PropertyInfo, Resolver))
                                : Assert.Throws <ModelValidationException>(() => Attr.Validate(value, PropertyInfo, Resolver));

            // Assert
            Assert.AreEqual(expectedExceptionMessage, ex.Message);
        }
Exemple #4
0
 public static void Validate(this PropertyDescriptor propertyDescriptor, object value)
 {
     foreach (object attrib in propertyDescriptor.Attributes)
     {
         ValidationAttribute validationAttribute = attrib as ValidationAttribute;
         if (validationAttribute != null)
         {
             validationAttribute.Validate(value, propertyDescriptor.Name);
         }
     }
 }
Exemple #5
0
        /// <summary>
        /// Copy from .NET 4.0 source code
        /// </summary>
        public static ValidationResult GetValidationResult(this ValidationAttribute att, object value, ValidationContext context)
        {
            var memberName = context.MemberName;

            try
            {
                att.Validate(value, memberName);
            }
            catch (Exception ex)
            {
                //NOTE: The MemberName could be set after the IsValid method is executed
                if (att is IHasMemberName)
                {
                    memberName = (att as IHasMemberName).MemberName ?? context.MemberName;
                }
                return(new ValidationResult(ex.Message, string.IsNullOrEmpty(memberName) ? null : new[] { memberName }));
            }
            return(null);
        }
        /// <summary>
        /// Maps Form data (for an HTTP POST request) to properies of a given Entity Model and performs basic validation.
        /// </summary>
        /// <param name="model">The Entity Model to map the form data to.</param>
        /// <returns><c>true</c> if there is any form data to be mapped.</returns>
        protected bool MapRequestFormData(EntityModel model)
        {
            if (Request.HttpMethod != "POST")
            {
                return(false);
            }

            // CSRF protection: If the anti CSRF cookie is present, a matching token must be in the form data too.
            const string antiCsrfToken = "__RequestVerificationToken";

            if (Request.Cookies[antiCsrfToken] != null)
            {
                AntiForgery.Validate();
            }

            Type modelType = model.GetType();

            foreach (string formField in Request.Form)
            {
                if (formField == antiCsrfToken)
                {
                    // This is not a form field, but the anti CSRF token (already validated above).
                    continue;
                }

                PropertyInfo modelProperty = modelType.GetProperty(formField);
                if (modelProperty == null)
                {
                    Log.Debug("Model [{0}] has no property for form field '{1}'", model, formField);
                    continue;
                }

                string formFieldValue = Request.Form[formField];

                ValidationAttribute validationAttr = modelProperty.GetCustomAttribute <ValidationAttribute>();
                if (validationAttr != null)
                {
                    try
                    {
                        validationAttr.Validate(formFieldValue, formField);
                    }
                    catch (ValidationException ex)
                    {
                        string validationMessage = ResolveValidationMessage(ex.Message, model);
                        Log.Debug("Validation of property '{0}' failed: {1}", formField, validationMessage);
                        ModelState.AddModelError(formField, validationMessage);
                        continue;
                    }
                }

                try
                {
                    if (modelProperty.PropertyType == typeof(bool))
                    {
                        // The @Html.CheckBoxFor method includes a hidden field with the original checkbox state, resulting in two boolean values (comma separated)
                        formFieldValue = formFieldValue.Split(',')[0];
                    }
                    modelProperty.SetValue(model, Convert.ChangeType(formFieldValue, modelProperty.PropertyType));
                }
                catch (Exception ex)
                {
                    Log.Debug("Failed to set Model [{0}] property '{1}' to value obtained from form data: '{2}'. {3}", model, formField, formFieldValue, ex.Message);
                    ModelState.AddModelError(formField, ex.Message);
                }
            }

            return(true);
        }
 protected void TestAttributeForValidValue(object value)
 {
     // Act
     Attr.Validate(value, PropertyInfo, Resolver);
 }