在.NET MVC 中,当页面提交model到Action的时候,自动填充ModelState。使用ModelState.IsValid进行方便快捷的数据验证,其验证也是调用命名空间System.ComponentModel.DataAnnotations中的各种方法进行验证。但是使用非MVC架构时,就需要写很多if判断或者正则表达式,当有多个字段需要验证的的时候不知道有多少人和我一样很厌烦这种用if判断的方式。这里记录一个方法,使用System.ComponentModel.DataAnnotations来实现自己的验证model抛出相应的错误信息。
C#文档地址:System.ComponentModel.DataAnnotations
 
这里我们先实现一个Person类,里面包含几个简单的属性,然后指定几个Attribute
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验证字段数据正确性的更多相关文章

  1. 对System.ComponentModel.DataAnnotations 的学习应用

    摘要 你还在为了验证一个Class对象中很多数据的有效性而写很多If条件判断吗?我也同样遇到这种问题,不过,最近学了一项新的方法,让我不在写很多if条件做判断,通过给属性标注特性来验证数据规则,从此再 ...

  2. System.ComponentModel.DataAnnotations 命名空间和RequiredAttribute 类

    System.ComponentModel.DataAnnotations 命名空间提供定义 ASP.NET MVC 和 ASP.NET 数据控件的类的特性. RequiredAttribute 指定 ...

  3. System.ComponentModel.DataAnnotations 冲突

    项目从原来的.NET Framework4.0 升级到 .NET Framework4.5 编译报错. 查找原因是: Entity Framework 与 .net4.5 的 System.Compo ...

  4. System.ComponentModel.DataAnnotations.Schema.TableAttribute 同时存在于EntityFramework.dll和System.ComponentModel.DataAnnotations.dll中

    Entity Framework 与 .net4.5 的 System.ComponentModel.DataAnnotations 都有 System.ComponentModel.DataAnno ...

  5. System.ComponentModel.DataAnnotations.Schema 冲突

    System.ComponentModel.DataAnnotations.Schema 冲突 Entity Framework 与 .net4.5 的 System.ComponentModel.D ...

  6. 解决EntityFramework与System.ComponentModel.DataAnnotations命名冲突

    比如,定义entity时指定一个外键, [ForeignKey("CustomerID")] public Customer Customer { get; set; } 编译时报 ...

  7. ASP.NET Core 6.0 基于模型验证的数据验证

    1 前言 在程序中,需要进行数据验证的场景经常存在,且数据验证是有必要的.前端进行数据验证,主要是为了减少服务器请求压力,和提高用户体验:后端进行数据验证,主要是为了保证数据的正确性,保证系统的健壮性 ...

  8. C# 特性 System.ComponentModel 命名空间属性方法大全,System.ComponentModel 命名空间的特性

    目录: System.ComponentModel 特性命名空间与常用类 System.ComponentModel.DataAnnotations ComponentModel - Classes ...

  9. “CreateRiaClientFilesTask”任务意外失败。 未能加载文件程序集“System.ComponentModel.DataAnnot...

    错误  77  “CreateRiaClientFilesTask”任务意外失败.  System.Web.HttpException (0x80004005): 未能加载文件或程序集“System. ...

随机推荐

  1. Bootstrap4中栅格系统CSS中 col-sm-* col-md-* col-lg-*的意义以及当其同时具有col-xs-* col-sm-* col-md-* col-lg-*的含义

    根据Bootstrap--Grid 中 col-sm-* col-md-* col-lg-* col-xl-*的意义: .col-sm-* 小屏幕 手机 (≥ 576px) .col-md-* 中等屏 ...

  2. mysql注入大全及防御

    0.明白存在的位置:get型 post型 cookie型 http头注入 1.先测试注入点,注册框.搜索框.地址栏啥的,判断是字符型,搜索型还是数字型 字符型 1' and '1'='1 成功, 1' ...

  3. opencv 读取视频内容写入图片帧

    现在主要把自己平时用到的opencv功能记录到博客,一方面方便自己有时间来回顾,另一方便提供给大家一个参考. opencv 读取视频内容,把视频帧每一帧写成图片,存入电脑中.这个步骤是许多数据处理的基 ...

  4. linux格式化磁盘命令

    linux格式化磁盘命令           linux mkfs         指令:mkfs 使用权限 : 超级使用者 使用方式 : mkfs [-V] [-t fstype] [fs-opti ...

  5. ieda与svn的配置与使用

    一.idea配置svn 快捷键Ctrl+Alt+s或者File--Settings-- Subversion 设置svn客户端(小乌龟)的svn.exe可执行程序(如果找不到,请看另一篇文章)     ...

  6. 一键部署lnmp脚本

    先下载好nginx安装包,解包之后可以执行下面的脚本,一键部署 cd nginx-1.12.2 useradd -s /sbin/nologin nginx./configuremakemake in ...

  7. SQL小操作

    用string.Format格式化参数 string sqlCmd = string.Format("select NO from [dbo].[SendAcerData] where BA ...

  8. source insight支持查看makefile、kconfig以及.s代码方法

    在用sourceinsight查看linux内核源码的时候,大家会发现不能查看源码中的makefile和kconfig代码,即不能搜索到makefile和kconfig文件.这是因为source in ...

  9. 如何连接虚拟的OneNote打印机

    include <Windows.h> #include <iostream> int main() { HANDLE handle = CreateFile(L"O ...

  10. DevExpress WPF v19.1新版亮点:Data Editors等控件新功能

    行业领先的.NET界面控件DevExpress 日前正式发布v19.1版本,本站将以连载的形式介绍各版本新增内容.在本系列文章中将为大家介绍DevExpress WPFv19.1中新增的一些控件及部分 ...