关闭

Attribute自定义特性验证

798人阅读 评论(0) 收藏 举报

1. 继承ValidationAttribute写特性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace ConsoleApplication3
{
    [AttributeUsage(AttributeTargets.Property)]
    public class RangeAttribute : ValidationAttribute
    {
        public double Min { set; get; }
        public double Max { set; get; }
        public string ErrorMessage{set;get;}
        public RangeAttribute()
            : base()
        { 
        }
        public RangeAttribute(string errorMessage, double min, double max)
            : base(errorMessage)
        {
            this.ErrorMessage = errorMessage;
            this.Min = min;
            this.Max = max;
        }
        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, ErrorMessage);
        }

        public override bool IsValid(object value)
        {
            bool flag = true;
            double validValue = Convert.ToDouble(value);
            if (validValue < Min || validValue > Max)
            {
                flag = false;
            }
            return flag;
        }
    }
}

2. 写测试实体Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication3
{
    public class Student
    {
        public int ID { set; get; }
        public string Name { set; get; }
        [Range("aaa",1,1000)]
        public string Num { set; get; }
    }
}
3. 写验证接口IValidator<T>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    public interface IValidator<T> where T:class
    {
        bool IsValid(T t);
    }
}

4.实现验证接口Validator<T>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication3
{
    public class Validator<T>:IValidator<T> where T:class
    {
        public bool IsValid(T t)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }

            Type type = t.GetType();
            PropertyInfo[] properties = type.GetProperties();

            foreach (PropertyInfo property in properties)
            {
                //获取验证特性
                object[] validateContent = property.GetCustomAttributes(typeof(ValidationAttribute), true);

                if (validateContent != null)
                {
                    //获取属性的值
                    object value = property.GetValue(t, null);
                    foreach (ValidationAttribute validateAttribute in validateContent)
                    {
                        if(!validateAttribute.IsValid(value))
			{
				return false;
			}
                    }
                }
            }
            return true;
        }
    }
}

5. 测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            student.ID = 1;
            student.Name = "";
            student.Num = "sdfsdfsd";
            Validator<Student> validator = new Validator<Student>();
            Console.WriteLine(validator.IsValid(student).ToString());
            Console.Write("start");
            
            Console.ReadKey();
        }
    }
}




1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:127024次
    • 积分:2303
    • 等级:
    • 排名:第16326名
    • 原创:68篇
    • 转载:2篇
    • 译文:3篇
    • 评论:129条
    博客专栏
    文章分类
    最新评论