Beispiel #1
0
        /// <summary>
        /// 验证属性
        /// </summary>
        private static void ValidateProperty(PropertyInfo property, object target, ValidationErrorCollection result)
        {
            var attributes = property.GetCustomAttributes(typeof(ValidationAttribute), true);

            foreach (var attribute in attributes)
            {
                var validationAttribute = attribute as ValidationAttribute;
                if (validationAttribute == null)
                {
                    continue;
                }
                ValidateAttribute(property, validationAttribute, target, result);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 验证
        /// </summary>
        public static ValidationErrorCollection Validate(object target)
        {
            var result = new ValidationErrorCollection();

            if (target == null)
            {
                result.Add(new ValidationError()
                {
                    FieldName = string.Empty, Message = "对象未实例化!"
                });
                return(result);
            }

            Type type       = target.GetType();
            var  properties = type.GetProperties();

            foreach (var property in properties)
            {
                ValidateProperty(property, target, result);
            }

            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// 验证特性
        /// </summary>
        private static void ValidateAttribute(PropertyInfo property, ValidationAttribute attribute, object target, ValidationErrorCollection result)
        {
            bool isValid = attribute.IsValid(property.GetValue(target));

            if (isValid)
            {
                return;
            }
            result.Add(new ValidationError()
            {
                FieldName = property.Name, Message = GetErrorMessage(property.Name, attribute)
            });
        }