zoukankan      html  css  js  c++  java
  • 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);

  • 相关阅读:
    Shiro
    Python活力练习Day11
    Python活力练习Day10
    Python活力练习Day9
    数据框DataFrame和列表List相互转换
    Python活力练习Day8
    Python中绘制箭头
    Python活力练习Day7
    Python活力练习Day6
    Python活力练习Day5
  • 原文地址:https://www.cnblogs.com/xinlang/p/1821252.html
Copyright © 2011-2022 走看看