asp.net 利用特性和正则表达式进行字段的验证(attribute)

1.创建自定义的特性类(继承Attribute类)。

  coding as below

    [AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=false)]
    public class FileVerification:Attribute
    {
        private string _regexStr;
        public string RegexStr
        {
            get { return _regexStr; }
            set { _regexStr = value; }
        }
        private string _showMessage;
        public string ShowMessage
        {
            get { return _showMessage; }
            set { _showMessage = value; }           
        }
    } 

2.在实体类属性上加上特性:

  coding as below

    public class Account
    {
        private string _user;
        private string _password;

        [FileVerification(RegexStr = @"^\w{1,50}$", ShowMessage = "请输入账号!")]
        public string User
        {
            get { return _user; }
            set { _user = value; }
        }
        [FileVerification(RegexStr = @"^\w{1,50}$", ShowMessage = "请输入密码!")]
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
    }

3.利用正则表达式对属性的值进行验证通用类:

   coding as below

  public class FieldVerification<T>
     {
          public static string Verification(T t)
          {
              string returenMessage = "";
              string fieldValue = "";
              FileVerification fv = null;
              Type customerType = typeof(T);
              PropertyInfo[] pIList = customerType.GetProperties();
              for (int i = 0; i < pIList.Length; i++)
              {
                  object[] oList = pIList[i].GetCustomAttributes(typeof(FileVerification), true);
                  foreach (object o in oList)
                  {
                      fv = (FileVerification)o;
                      fieldValue = Convert.ToString(pIList[i].GetValue(t, null));
                      if (!Regex.IsMatch(fieldValue, fv.RegexStr))
                      {
                          returenMessage += fv.ShowMessage;
                      }
                  }

              }
              return returenMessage;
          }
     }

4.调用验证类:

coding as below

            Account a = new Account();
            a.User = "";
            a.Password = "";
            errorMessage = FieldVerification<Account>.Verification(a);

原文地址:https://www.cnblogs.com/xinlang/p/1821252.html