【Attribute】自定义ValidationAttribute+扩展方法 实现类对象字段数据验证

常常有这样的需求:方法接受一个对象参数,要验证对象的所有字段的值是否合乎要求,如进行非空检测,长度检测等等。

比如,有这样一个Stu的类

   public class Stu
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public byte[] FileBytes { get; set; }

    }

new 一个 对象 作为参数进行传递

        static void Main(string[] args)
        {
            Stu student = new Stu()
            {
                Age = 45,
                FileBytes = new Byte[1024 * 10000]
            };

//……要在这里检测student对象的各个属性值是否合法……
Console.ReadKey(); }

怎么来判断student的合法性呢?检测student的Name字段是否有值,检测FileBytes字段是否超出指定长度

1、Required 非空检测

引用System.ComponentModel.DataAnnotations,在Stu类的Name字段上加上[Required]属性标签

2、自定义属性检测

检测FileBytes的长度,需要自定义来实现

定义一个ByteArrayMaxSizeCheckAttribute自定义属性类,继承自ValidationAttribute,如下

 public class ByteArrayMaxSizeCheckAttribute : ValidationAttribute
    {
        /// <summary>
        /// 最大大小
        /// </summary>
        private int maxsize;
        public ByteArrayMaxSizeCheckAttribute()
        {

        }
        public ByteArrayMaxSizeCheckAttribute(int size)
        {
            maxsize = size;
        }
        public override bool IsValid(object value)
        {
            if (value == null)
            {
                return true;
            }
            var content = value as byte[];
            double filesize = content.Length / 1024 * 1.0;
            filesize = filesize / 1024 * 1.0;
            if (filesize > maxsize)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

然后,同样,在Stu类的FileBytes字段上加上两个标签

        [Required]
        [ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}大小超出最大限制")]

 

Stu就应该是下面的样子

   public class Stu
    {
        [Required]
        public string Name { get; set; }
        public int Age { get; set; }
       
        [Required]
        [ByteArrayMaxSizeCheck(1, ErrorMessage = "{0}大小超出最大限制")]
        public byte[] FileBytes { get; set; }

    }
3、编写扩展方法,实现验证逻辑
 public static class ValidExtension
    {
        public static string ErrorMsg<T>(this T model) where T : class, new()
        {
            var propertis = model.GetType().GetProperties();
            string errorMsg = "";
            foreach (var info in propertis)
            {
                var attributes = info.GetCustomAttributes();
                foreach (var attribute in attributes)
                {
                    if (attribute is ValidationAttribute)
                    {
                        var reqattr = attribute as RequiredAttribute;
                        var maxsizeattr = attribute as ByteArrayMaxSizeCheckAttribute;
                        if (reqattr != null)
                        {
                            var obj = info.GetValue(model);
                            if (!reqattr.IsValid(obj))
                            {
                                errorMsg = errorMsg + reqattr.FormatErrorMessage(info.Name);
                            }
                        }
                        if (maxsizeattr != null)
                        {
                            var obj = info.GetValue(model);
                            if (!maxsizeattr.IsValid(obj))
                            {
                                errorMsg = errorMsg + maxsizeattr.FormatErrorMessage(info.Name);
                            }
                        }
                    }
                }
            }
            return errorMsg;
        }
    }

 

下面来看怎么调用验证
        static void Main(string[] args)
        {
            Stu student = new Stu()
            {
                Age = 45,
                FileBytes = new Byte[1024 * 10000]
            };
            var errorMessage = student.ErrorMsg();
            Console.WriteLine(errorMessage);
            Console.ReadKey();
        }

转载于:https://www.cnblogs.com/cqupt/p/7019011.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值