示例#1
0
        /// <summary>
        /// Helper method to chain into Add(TValidationAttribute validationAttribute) but don't need to create attribute
        /// </summary>
        /// <typeparam name="TValidationAttribute"></typeparam>
        /// <param name="setter"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public IPropertyValidations <TSource, TProperty> AddIfValid <TValidationAttribute>(
            Action <TValidationAttribute> setter,
            params Expression <Func <TSource, object> >[] properties)
            where TValidationAttribute : ValidationAttribute, new()
        {
            var attribute = new TValidationAttribute();

            setter?.Invoke(attribute);

            var propsToValidate = properties.ToDictionary(p => p.NameOf(), p =>
            {
                var func = p.Compile();
                Func <object, object> convert = o => func((TSource)o);
                return(convert);
            });

            var validationAttribute = new ValidateIfAttribute(propsToValidate, attribute);

            return(Add(validationAttribute));
        }
示例#2
0
        /// <summary>
        /// Adds a func/method to get called when this property is validated
        /// If the other properties pass in pass validation
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="propertyValidations"></param>
        /// <param name="validation"></param>
        /// <param name="setter"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public static IPropertyValidations <TSource, TProperty> AddIfValid <TSource, TProperty>(
            this IPropertyValidations <TSource, TProperty> propertyValidations,
            Func <TProperty, TSource, ValidationContext, ValidationResult> validation,
            Action <ValidationAttribute> setter,
            params Expression <Func <TSource, object> >[] properties)
        {
            Func <object, ValidationContext, ValidationResult> map =
                (prop, context) => validation((TProperty)prop, (TSource)context.ObjectInstance, context);
            var attribute = new ValidatableObjectAttribute(map);

            setter?.Invoke(attribute);

            var propsToValidate = properties.ToDictionary(p => p.NameOf(), p =>
            {
                var func = p.Compile();
                Func <object, object> convert = o => func((TSource)o);
                return(convert);
            });

            var validationAttribute = new ValidateIfAttribute(propsToValidate, attribute);

            return(propertyValidations.Add(validationAttribute));
        }