使用System.ComponentModel.DataAnnotations验证字段数据正确性
C#文档地址:System.ComponentModel.DataAnnotations
public class Person
{
[Required(ErrorMessage = "{0} 必须填写")]
[DisplayName("姓名")]
public string Name { get; set; } [Required(ErrorMessage = "{0} 必须填写")]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "邮件格式不正确")]
public string Email { get; set; } [Required(ErrorMessage = "{0} 必须填写")]
[Range(, , ErrorMessage = "超出范围")]
public int Age { get; set; } [Required(ErrorMessage = "{0} 必须填写")]
[StringLength(, MinimumLength = , ErrorMessage = "{0}输入长度不正确")]
public string Phone { get; set; } [Required(ErrorMessage = "{0} 必须填写")]
[Range(typeof(decimal), "1000.00", "2000.99")]
public decimal Salary { get; set; }
}
然后实现一个ValidatetionHelper静态类,这里主要用到的是Validator.TryValidateObject方法。
public static class ValidatetionHelper
{
public static ValidResult IsValid(object value)
{
ValidResult result = new ValidResult();
try
{
var validationContext = new ValidationContext(value, null, null);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(value, validationContext, results, true); if (!isValid)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
foreach (var item in results)
{
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = item.ErrorMessage,
ErrorMemberName = item.MemberNames.FirstOrDefault()
});
}
}
else
{
result.IsVaild = true;
}
}
catch (Exception ex)
{
result.IsVaild = false;
result.ErrorMembers = new List<ErrorMember>();
result.ErrorMembers.Add(new ErrorMember()
{
ErrorMessage = ex.Message,
ErrorMemberName = "Internal error"
});
} return result;
}
}
其中需要的返回结果类
public class ValidResult
{
public List<ErrorMember> ErrorMembers { get; set; }
public bool IsVaild { get; set; }
} public class ErrorMember
{
public string ErrorMessage { get; set; }
public string ErrorMemberName { get; set; }
}
实现一个测试代码,这里看到对应验证数据比使用多个if简洁很多,整个代码也十分美观。
static void Main(string[] args)
{
Person person = new Person();
person.Name = "";
person.Email = "121 212 K";
person.Phone = "";
person.Salary = ;
var result = ValidatetionHelper.IsValid(person);
if (!result.IsVaild)
{
foreach (ErrorMember errorMember in result.ErrorMembers)
{
Console.WriteLine(errorMember.ErrorMemberName + ":" + errorMember.ErrorMessage);
}
}
Console.Read();
}
通过测试,可以看到得到正确的验证结果。

后续有时间,把DisplayName给显示上去,那就更完美了。
参考:使用System.ComponentModel.DataAnnotations验证字段数据正确性
使用System.ComponentModel.DataAnnotations验证字段数据正确性的更多相关文章
- 对System.ComponentModel.DataAnnotations 的学习应用
摘要 你还在为了验证一个Class对象中很多数据的有效性而写很多If条件判断吗?我也同样遇到这种问题,不过,最近学了一项新的方法,让我不在写很多if条件做判断,通过给属性标注特性来验证数据规则,从此再 ...
- System.ComponentModel.DataAnnotations 命名空间和RequiredAttribute 类
System.ComponentModel.DataAnnotations 命名空间提供定义 ASP.NET MVC 和 ASP.NET 数据控件的类的特性. RequiredAttribute 指定 ...
- System.ComponentModel.DataAnnotations 冲突
项目从原来的.NET Framework4.0 升级到 .NET Framework4.5 编译报错. 查找原因是: Entity Framework 与 .net4.5 的 System.Compo ...
- System.ComponentModel.DataAnnotations.Schema.TableAttribute 同时存在于EntityFramework.dll和System.ComponentModel.DataAnnotations.dll中
Entity Framework 与 .net4.5 的 System.ComponentModel.DataAnnotations 都有 System.ComponentModel.DataAnno ...
- System.ComponentModel.DataAnnotations.Schema 冲突
System.ComponentModel.DataAnnotations.Schema 冲突 Entity Framework 与 .net4.5 的 System.ComponentModel.D ...
- 解决EntityFramework与System.ComponentModel.DataAnnotations命名冲突
比如,定义entity时指定一个外键, [ForeignKey("CustomerID")] public Customer Customer { get; set; } 编译时报 ...
- ASP.NET Core 6.0 基于模型验证的数据验证
1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...
- C# 特性 System.ComponentModel 命名空间属性方法大全,System.ComponentModel 命名空间的特性
目录: System.ComponentModel 特性命名空间与常用类 System.ComponentModel.DataAnnotations ComponentModel - Classes ...
- “CreateRiaClientFilesTask”任务意外失败。 未能加载文件程序集“System.ComponentModel.DataAnnot...
错误 77 “CreateRiaClientFilesTask”任务意外失败. System.Web.HttpException (0x80004005): 未能加载文件或程序集“System. ...
随机推荐
- PHP hex文件及bin文件读取
背景:做物联网时经常会有软件上传这种操作,上传的软件包文件常见的是hex和bin这两种. 一 hex文件读取 1 首先我们需要了解hex文件内容格式 (图及下面说明来自网络,侵权必删) :(冒号)每个 ...
- angular集成tinymce
1.前言 我使用的是angular的7.x版本,和之前的低版本集成方式有所区别.这里记录下基本的集成步骤. 2.集成步骤 2.1安装tinymac包 npm install tinymce --sav ...
- ftp建立虚拟用户实现文件上传和下载
环境 centos7 1.开启vsftpd服务 2.检查vsftpd服务是否开启 3.添加虚拟用户口令文件 vi etc/vsftpd/vuser.txt 4.生成虚拟用户口令认证文件 如果没有db_ ...
- Big Data(二)分布式文件系统那么多,为什么hadoop还需要一个hdfs文件系统?
提纲 - 存储模型- 架构设计- 角色功能- 元数据持久化- 安全模式- 副本放置策略- 读写流程- 安全策略 存储模型 - 文件线性按字节切割成块(block),具有offset,id - 文件与文 ...
- 文件上传 MIME类型检测
简介 MIME(Multipurpose Internet Mail Extensions)多用途网络邮件扩展类型,可被称为Media type或Content type, 它设定某种类型的文件当被浏 ...
- Python核心技术与实战——十二|Python的比较与拷贝
我们在前面已经接触到了很多Python对象比较的例子,例如这样的 a = b = a == b 或者是将一个对象进行拷贝 l1 = [,,,,] l2 = l1 l3 = list(l1) 那么现在试 ...
- Python之网路编程利用multiprocessing开进程
一.multiprocessing模块介绍 python中的多线程无法利用CPU资源,在python中大部分情况使用多进程.python中提供了非常好的多进程包multiprocessing. mul ...
- postman批量调用接口并发测试
本文出自:https://www.cnblogs.com/2186009311CFF/p/11425913.html 接口测试在开发中很容易遇到,下面是请教别人学会的并发测试,希望能帮到需要用到的你, ...
- mybatis config 配置设置说明
<!– 配置设置 –> 2. <settings> 3. <!– 配置全局性 cache 的 ( 开 / 关) defau ...
- 30 分钟理解 CORB 是什么
写在前面 前些日子在调试 bug 的时候,偶然发现这么一个警告: Cross-Origin Read Blocking (CORB) blocked cross-origin response htt ...