Example #1
0
        public IEnumerable <ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage   = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "requiredifany",
            };

            var properties = new List <string>();
            var values     = new List <object>();

            for (int i = 0; i < DependentProperties.Count(); i++)
            {
                string depProp = BuildDependentPropertyId(metadata, context as ViewContext, DependentProperties[i]);

                // find the value on the control we depend on;
                // if it's a bool, format it javascript style
                // (the default is True or False!)
                string targetValue = (TargetValues[i] ?? "").ToString();
                if (TargetValues[i].GetType() == typeof(bool))
                {
                    targetValue = targetValue.ToLower();
                }

                properties.Add(depProp);
                values.Add(targetValue);
            }

            rule.ValidationParameters.Add("dependentproperties", String.Join("|", properties));
            rule.ValidationParameters.Add("targetvalues", String.Join("|", values));

            yield return(rule);
        }
Example #2
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            for (int i = 0; i < DependentProperties.Count(); i++)
            {
                // get a reference to the property this validation depends upon
                var containerType = validationContext.ObjectInstance.GetType();
                var field         = containerType.GetProperty(this.DependentProperties[i]);

                if (field != null)
                {
                    // get the value of the dependent property
                    var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

                    // compare the value against the target value
                    if ((dependentvalue == null && this.TargetValues[i] == null) ||
                        (dependentvalue != null && dependentvalue.Equals(this.TargetValues[i])))
                    {
                        // match => means we should try validating this field
                        if (!_innerAttribute.IsValid(value))
                        {
                            // validation failed - return an error
                            return(new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }));
                        }
                    }
                }
            }

            return(ValidationResult.Success);
        }