自定义特性验证数据
2016-03-14 18:36
363 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ValidateConsoleApplication { class Program { static void Main(string[] args) { Console.WriteLine("----------------------------------------"); var u = new User { Name = "jinshuaijinshuaijinshuaijinshuaijinshuai", Age = 0 }; var result= ValidateCore.Validte<User>(u); foreach (var r in result) { Console.WriteLine(r); } Console.WriteLine("----------------------------------------"); Console.Read(); } } public class User { [RegexValidate(ErrorMessage = "用户名信息太长或太短!", Regex = "^\\w{5,10}$")] [RegexValidate(ErrorMessage="用户名必须以s开头!",Regex="^s\\w+$")] public string Name { get; set; } [RegexValidate(ErrorMessage = "年龄输入错误!", Regex = "^[1-9]{1,3}$")] public int Age { get; set; } } public interface IValidate { string ErrorMessage { get; set; } bool Validate<T>(T para); string Regex { get; set; } } [AttributeUsage(AttributeTargets.Property,AllowMultiple=true, Inherited = false)] [Serializable] public class RegexValidate : Attribute, IValidate { public string ErrorMessage { get; set; } public bool Validate<T>(T para) { var value = para.ToString(); var r = new Regex(Regex); return r.IsMatch(value); } public string Regex { get; set; } } public class ValidateCore { public static List<string> Validte<T>(T model) where T:class { var errorMessage = new List<string>(); var t = model.GetType(); var p = t.GetProperties(); foreach (var c in p) { var a = c.GetCustomAttributes(typeof(IValidate), true); foreach (var b in a) { var d = b as IValidate; if (d == null) { continue; } bool v = d.Validate(c.GetValue(model, null)); if (!v) { errorMessage.Add(d.ErrorMessage); } } } return errorMessage; } } }
相关文章推荐
- zookeeper集群搭建
- LeetCode332. Reconstruct Itinerary
- latex 基本用法(四)
- PHP 批量生成静态文件目录代码
- 编程规范的一些小事
- js判断浏览器类型
- 带分数问题
- python学习笔记(2)-IO编程
- Xutils简介及使用详解
- Python 模块学习:os模块
- css 画圆,环形,椭圆
- java设计模式4-装饰者模式
- Android内置的Action
- CodeForces 618A-Slime Combining【模拟】
- 正则表达式30分钟教程
- 关于Android APP集成腾讯X5 WebKit
- c#中abstract、override、new、virtual、sealed使用和示例
- 继腾讯一面和阿里二面之后!!!
- Head First PMP – 8 – 质量管理(Quality Management)
- 优雅降级和渐进增强的区别[转]