예제 #1
0
        /// <summary>
        ///   Adds a dynamic property to a rule, which will be copied to any <see cref="FailedEvaluation" /> generated by the rule.
        /// </summary>
        /// <typeparam name="TTarget"> The <see cref="Type" /> of the target. </typeparam>
        /// <typeparam name="T"> The <see cref="Type" /> of the dynamic property. </typeparam>
        /// <param name="plan"> The validation plan. </param>
        /// <param name="value"> The value. </param>
        /// <returns> A clone of the source validation rule. </returns>
        public static ValidationPlan <TTarget> With <TTarget, T>(this ValidationPlan <TTarget> plan, T value)
        {
            var clone = (ValidationPlan <TTarget>)plan.Clone();

            clone.Set(value);
            return(clone);
        }
예제 #2
0
        /// <summary>
        ///   Adds validatiom rules for any DataAnnotations attributes on the validated type.
        /// </summary>
        /// <typeparam name="T"> The type to be validated. </typeparam>
        /// <param name="plan"> The validation plan to which to add DataAnnotations validation rules. </param>
        /// <returns> </returns>
        public static ValidationPlan <T> ConfigureFromAttributes <T>(this ValidationPlan <T> plan)
        {
            ValidationRule <T> rule = null;

            rule = Validate.That <T>(t =>
            {
                var context = new ValidationContext(t, null, null);
                var results = new List <ValidationResult>();
                var isValid = Validator.TryValidateObject(t, context, results, true);

                // add results to the validation scope
                results.ForEach(result =>
                {
                    result
                    .MemberNames
                    .ForEach(member =>
                             ValidationScope.Current.AddEvaluation(
                                 new FailedEvaluation(
                                     target: t,
                                     rule: rule)
                    {
                        Message    = result.ErrorMessage,
                        MemberPath = member
                    }));
                });

                return(isValid);
            });

            var clone = (ValidationPlan <T>)plan.Clone();

            clone.AddRule(rule);
            return(clone);
        }