当前位置: 爱符号 - 所有分类 - Web开发 - ASP.NET - asp.net 利用特性和正则表达式进行字段的验证(attribute)
asp.net 利用特性和正则表达式进行字段的验证(attribute) asp.net LiYongTeXingHeZhengZeBiaoDaShiJinXingZiDuanDeYanZheng(attribute)
小伟 发表于:2012-10-23 16:14:38 阅读(1434)
关键词:asp.net asp.net attribute 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);

声明:以上内容仅代表作者观点,不代表爱符号赞成此内容或立场