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

本文介绍如何在C#中使用自定义属性进行数据验证,包括创建自定义特性类、应用特性到实体类属性及编写通用验证方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/archive/2010/09/08/1821252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值