C#中自定义特性验证实体类数据

一、抽象基类BaseAttribute

/// <summary>
    /// BaseAttribute 的摘要说明
    /// </summary>
    public abstract class BaseAttribute : Attribute
    {
        public abstract string Validate(object value);
    }

二、自定义特性类

定义两个特性,RangeAttribute和MailAttribute,分别用来验证数字范围和邮箱正则匹配

  • RangeAttribute
/// <summary>
    /// 数值验证
    /// </summary>
    public class RangeAttribute : BaseAttribute
    {
        private readonly int _min, _max;
        public RangeAttribute(int min, int max)
        {
            _min = min;
            _max = max;
        }
        public override string Validate(object value)
        {
            try
            {
                int _value = Convert.ToInt32(value);
                if (_value < _min || _value > _max)
                {
                    return string.Format("验证失败:数值应处于{0}和{1}之间", _min, _max);
                }
            }
            catch (Exception ex)
            {
                return "验证异常:" + ex.Message;
            }
            return "";
        }
    }
  • MailAttribute
/// <summary>
    /// 邮箱验证
    /// </summary>
    public class MailAttribute : BaseAttribute
    {
        public override string Validate(object value)
        {
            try
            {
                string _value = Convert.ToString(value);
                if (!Regex.IsMatch(_value, "^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"))
                {
                    return "验证失败:请输入正确的邮箱地址";
                }
            }
            catch (Exception ex)
            {

                return "验证异常:" + ex.Message;
            }
            return "";
        }
    }

三、定义实体学生类

学生实体类的字段上使用自定义特性

/// <summary>
/// Student 的摘要说明
/// </summary>
public class Student
{
    public string Name { get; set; }
    [Range(18, 28)]
    public int Age { get; set; }
    [Mail]
    public string mail { get; set; }
}

四、静态拓展方法

通过反射找到学生实体的标注自定义特性,依次进行对实体字段进行验证

/// <summary>
    /// 扩展类
    /// </summary>
    public static class ValidateEx
    {
        /// <summary>
        /// 实体扩展方法
        /// 验证方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string Validate<T>(this T model) where T : class
        {
            string msg = null;

            //获取类型
            Type type = model.GetType();

            //反射找到属性值
            var properties = type.GetProperties();
            foreach (var prop in properties)
            {
                //是否将指定类型或其派生类型的一个或多个特性应用于此成员
                if (prop.IsDefined(typeof(BaseAttribute), true))
                {
                    var attributes = prop.GetCustomAttributes(typeof(BaseAttribute), true);//获取自定义的特性
                    foreach (BaseAttribute attr in attributes)
                    {
                        msg += attr.Validate(prop.GetValue(model)) + "\r\n";
                    }
                }
            }
            return msg;
        }
    }

五、测试验证方法

/// <summary>
/// 按钮测试方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
    Student model = new Student
    {
        Name = txt_name.Text,
        Age = int.Parse(txt_age.Text),
        mail = txt_mail.Text
    };
    string msg = model.Validate();

    if (!string.IsNullOrWhiteSpace(msg))
    {
        MessageBox.Show(msg);
    }
    else
    {
        MessageBox.Show("验证通过");
    }
}

image

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值