Several people have asked me about using data annotations for validation outside of a UI framework, like ASP.NET MVC or Silverlight. The System.ComponentModel.DataAnnotations assembly contains everything you need to execute validation logic in the annotations. Specifically, there is a static Validator class to execute the validation rules. For example, let's say you have the following class in a console mode application:

public class Recipe
{
[Required]
public string Name { get; set; }
}

You could validate the recipe with the following code:

var recipe = new Recipe();
var context = new ValidationContext(recipe, serviceProvider: null, items: null);
var results = new List<ValidationResult>(); var isValid = Validator.TryValidateObject(recipe, context, results); if (!isValid)
{
foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
}
}

Result: "The Name field is required".

You can construct the ValidationContext class without a service provider or items collection, as shown in the above code, as they are optional for the built-in validation attributes. The Validator also executes any custom attributes you have defined, and for custom attributes you might find the serviceProvider useful as a service locator, while the items parameter is a dictionary of extra data to pass along. The Validator also works with self validating objects that implement IValidatableObject.

public class Recipe : IValidatableObject
{
[Required]
public string Name { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
// ...
}
}

Like everything framework related, the Validator tries to provide an API that will work in a number of validation scenarios. I recommend you bend it to your will and build something that makes it easy to use inside your specific design and architecture. A class like the following would be a step towards hiding some complexity.

public class DataAnnotationsValidator
{
public bool TryValidate(object @object, out ICollection<ValidationResult> results)
{
var context = new ValidationContext(@object, serviceProvider: null, items: null);
results = new List<ValidationResult>();
return Validator.TryValidateObject(
@object, context, results,
validateAllProperties: true
);
}
}

https://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

Manual Validation with Data Annotations C#对实体类进行手动验证的更多相关文章

  1. C# Web 数据注解Data Annotations、模型状态ModelState、数据验证

    C#中的模型状态与数据注解,为我们提供了很便利的请求数据的验证. 1. ModelState ModelState在进行数据验证的时候很有用的,它是: 1)验证数据,以及保存数据对应的错误信息. 2) ...

  2. Spring Data JPA 多个实体类表联合视图查询

    Spring Data JPA 查询数据库时,如果两个表有关联,那么就设个外键,在查询的时候用Specification创建Join 查询便可.但是只支持左连接,不支持右连接,虽说左右连接反过来就能实 ...

  3. WPF3.5 使用BINDINGGROUP进行实体类和集合验证

    前文介绍了自定义或系统自带的ValidationRule进行验证,这种方法对于单个元素的验证不错.很多时候,我们需要对表单(Form)进行验证,也就是对一个实体类进行验证,或者对一个集合的每项进行验证 ...

  4. 关于entityframework 自动生成实体类中加验证的属性重新生成后属性被覆盖解决办法

    1.手动创建一个部分类 (你可以手动创建 partial class, 内容为空) [MetadataType(typeof(AppleMetadata))] public partial class ...

  5. Entity Framework 6 Code First系列1: 实体类1:1配置

    从4.1版本开始,EF开始支持Code First模式,值得注意的是Code First不是和DataBase First或Model First平级的概念,而是和EDM平级的概念.使用Code Fi ...

  6. EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射

    I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF里的默认映射.具体分为: 数据库映射:Code First ...

  7. EF——默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射 02 (转)

    EF里的默认映射以及如何使用Data Annotations和Fluent API配置数据库的映射   I.EF里的默认映射 上篇文章演示的通过定义实体类就可以自动生成数据库,并且EF自动设置了数据库 ...

  8. 使用Data Annotations进行手动数据验证

    Data Annotations是在Asp.Net中用于表单验证的 它通过Attribute直接标记字段的有效性,简单且直观.在非Asp.Net程序中(如控制台程序),我们也可以使用Data Anno ...

  9. Data Annotations

    Data Annotations   Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己 ...

随机推荐

  1. 我要当皇帝等微信小游戏的wbs

    猜字:1.视图交互: 1)主界面:展示每一道题目跟答案 1) 题目展示区域, 成员布局 2) 选项展示 3) 其他 2)下一道题弹框 3)答案弹框 4)结果弹框 5)关卡弹框 2.数据处理, 1) 读 ...

  2. bzoj 1008

    记得取模时对答案的处理 #include<bits/stdc++.h> #define ll long long using namespace std; ; ll qpow(ll a,l ...

  3. 招聘移动APP、接口、自动化、性能和安全方面的兼职测试讲师

    只要您在移动APP.接口.自动化.性能和安全方面有丰富的测试经验,我们都欢迎您能加入我们,成为我们的兼职测试讲师,我们可以提供给您一份优厚的薪资,同时能在行业发展.企业培训.授课经验.出版专业著作等方 ...

  4. nginx -- 单独访问某个页面404

  5. C#保存文件为无BOM的utf8格式

    如图所示,发现用C#的 File.WriteAllLines 方法,无论怎么设置,最终生成的文件都是 PC utf8,也就是CRLF,用SVN进行提交的时候,显示左侧为utf8,右侧为utf8 BOM ...

  6. cocos creator热更新教程

    1.下载HotUpdate热更新DEMO 2.在cocos creator中下载热更新插件,cocos creator版本要在1.7及以上版本 3.插件默认安装在C:\Users\Administra ...

  7. Lua MD5加密字符串

    function md5_sumhexa(k) local md5_core = require "md5.core" k = md5_core.sum(k) return (st ...

  8. Creating an LMDB database in Python

    LMDB is the database of choice when using Caffe with large datasets. This is a tutorial of how to cr ...

  9. Exchange Online Mailbox Restoration

    User Account is already deleted in AD.User Mailbox is already deleted in Exchange. 1. Connect to Exc ...

  10. Android 安全开发之 ZIP 文件目录遍历

    1.ZIP文件目录遍历简介 因为ZIP压缩包文件中允许存在"../"的字符串,攻击者可以利用多个"../"在解压时改变ZIP包中某个文件的存放位置,覆盖掉应用原 ...