`
nlx0201
  • 浏览: 28800 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Attribute自定义特性验证

 
阅读更多

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();
        }
    }
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics