1. 程式人生 > 其它 >C#中的Attribute驗證

C#中的Attribute驗證

一、定義特性

  • 定義驗證抽象類
 public abstract class AbstractValidateAttribute:Attribute
    {
        //和介面類似,抽象方法只宣告方法
        public abstract bool Validate(object objValue);
    }
  • 長度驗證特性類
[AttributeUsage(AttributeTargets.Property)]
    public class LongAttribute : AbstractValidateAttribute
    {
        private long _Long = 0;
        public LongAttribute(long phoneLength)
        {
            this._Long = phoneLength;
        }

        public override bool Validate(object objValue)
        {
           return objValue != null && objValue.ToString().Length == 11;
        }
    }
  • 非空驗證特性類
 [AttributeUsage(AttributeTargets.Property)]
    public class RequiredAttribute : AbstractValidateAttribute
    {
        public override bool Validate(object objValue)
        {
            return objValue != null && !string.IsNullOrWhiteSpace(objValue.ToString());
        }
    }
  • 字串長度驗證類
 [AttributeUsage(AttributeTargets.Property)]
    public class StringLengthAttribute : AbstractValidateAttribute
    {
        //欄位
        private int _Mni=0;
        private int _Max = 0;

        public StringLengthAttribute(int min,int max)
        {
            this._Max = max;
            this._Mni = min;
        }
        public override bool Validate(object objValue)
        {
          return  objValue != null
                && objValue.ToString().Length >= this._Mni
                && objValue.ToString().Length <= this._Max;
        }
    }
  • 驗證拓展類
 public static class AttributeExtend
    {
        public static bool Validate<T>(this T t)
        {
            Type type = t.GetType();
            foreach (var property in type.GetProperties())//屬性上查詢
            {
                if (property.IsDefined(typeof(AbstractValidateAttribute),true))
                {
                    object objValue = property.GetValue(t);
                    foreach (AbstractValidateAttribute attribute in property.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
                    {
                        if (!attribute.Validate(objValue))//如果成功了以後 就繼續驗證,否則就直接返回
                        {
                            return false ;
                        }
                    }
                }
                
            }
            return true;
        }
    }
  • 學生實體類

    在學生實體類的屬性上,使用特性驗證

 public class Student
    {
        public int Id { get; set; }
        [Required]
        [StringLength(2,3)]
        public string StudentName { get; set; }
        [Required]
        [Long(11)]
        public long PoneNumber { get; set; }
    }

二、呼叫驗證特性

 Student student = new Student()
            {
                Id = 1,
                PoneNumber = 12345678900,
                StudentName = "小剛"
            };

            if (student.Validate())
            {
                Console.WriteLine("驗證成功");
            }
            else
            {
                Console.WriteLine("驗證失敗");
            }