Data Annotations是在Asp.Net中用于表单验证的

它通过Attribute直接标记字段的有效性,简单且直观。在非Asp.Net程序中(如控制台程序),我们也可以使用Data Annotations进行手动数据验证的,一个简单的例子如下(需要添加System.ComponentModel.DataAnnotations.dll的引用):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var user = new User();
var context = new ValidationContext(user, null, null); var results = new List<ValidationResult>();
Validator.TryValidateObject(user, context, results, true); foreach (var validationResult in results)
{
Console.WriteLine(validationResult.ErrorMessage);
} Console.Read();
}
} class User
{
[Required]
public string Name { get; set; } [Range(, )]
public int Age { get; set; }
}
}

输出:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhgAAABbCAIAAAC+tWusAAAR5UlEQVR4nO2d+1MVV7bH1z8jWAUnVUJ+nJ8SJKl7E0acyshDRSP5YcYJkXn64HHIOBFEROL1akwIKGBAUDExLxUEhFKimQyZTG7ilTJaBmdu1TgaE8CMucwPfbp793717u4j5xzn+6lvpbp3r7322mvv3usc0EiPAwAAABGgBQAAACACdODUnyAIgiAotOi1U1MQBEEQFFr02rtTEARBEBRadPC9TyEIgiAotOj19/8MQRAEQaFF7R98BkEQBEGhRW9++BkEQRAEhRZ1nP4cgiAIgkKLDp35HwiCIAgKrUQhadjeaKhXOwY7T/8l5XFDEARBaSI6fPaLw2e/uDB5SarJjy5/dPnjyUsfX/zostXSsL3x9VOfWL0gCIIgiLqHv+we/nL2/j8N1bC98Y1Tf7R6MTq9OoeI6ImNW5fQstVdX3YPv/4ErfoNb5ZU7VhFOVtbtDYtG5eREjG806tzrOBlY8lh7JU2ZnkwmE6GqcvZDFH0cDaSk+3kBJkeepTmsggHCDtKlNQ9OmkPn3PqOXel59yVBw8enB2aeq6uf9XLfaU7estbetbuPXxrZub+/JyjH/288/78XMP2xvZ3P7F6Odq9cRk980bPuSs93duW0LI13Vd6zr3xBK36rddMp+5tS1h7/a2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AAAQCRQSAAAAEThXyxwYFtQbZ9lAAAAAElFTkSuQmCC" alt="" />

若添加了 user.Name = "test";这一句,只把age不符合要求的输出来

  var user = new User();
user.Name = "test";
var context = new ValidationContext(user, null, null);

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAecAAABWCAIAAAB6jslnAAAQqUlEQVR4nO2c+1cVV5bHzz8juBbcrCX0j/NTgiRrJqHFWWl5qGgkP/TYITI9Pe2DxyVjRxARiW3rJCGggA0+MZ1+RN6vFtR0BqNJNNJGlo098R0TwLSZPT/UrapTdR731AWlLvl+1veHuufus8/e++zasMiDEdF7H16EIAiCkkKMiJpOfwpBEAQlhRgRHez6DIIgCEoK6aZ21fZqQ73V1Nl8+tKCJwNBELToxYjoUPfnUp0ZOyfV2NnzZ89/NHbuo9Gz562Vqu3V73zwscoPBEEQNF9iRNTae1mq6Uf/MFTV9up3P/iL4OH06jTGGHt249YlbNnqlsutve88y1b9QnHc/GjHKpa2tU5rU7dxGVMihnd6dZoVvOwsOZy90sasDgbpJJlanGaYi55MIznVnp8gw6HFlMtTGCD8KXMp3ZMsOyOitr4rUj1+/Li7Z/zliqOr3ujI39FeWNe2du+hm1NTj2ZnHP3TvzU/mp2p2l7d+PuPfdt3b1zGXny3re9KW+u2JWzZmtYrbX3vPstW/afiOIlaty3h7fUfLVWvYmnbdmu97d64bMnGLnfRCrLvSltf15o0WXgqn9WrmLv3CufESlYjWR2CphNySdPp45thLgrYSIZyqh00yNZtS+yfxs9W80HGfop7XFWv8pqpLd0ydq1Jc3/ge/eaxDb3guvv14mfyd6IeZTJvXetSZtjGPYpcyndXPZKOsRTc0ZEv+2/KtX3jx9394yX7Pug9O3f/byp8xetJzZ3HFVN7ff+MO7b/ssXWcrPeryLjc+xvF8qjhNV/7MM3oP+Y0w1eSytrF7rzbOxrSzlxUbbpmdtmh1eTZ7y13HHf00ec/de5ZxkrG276vqXe/HXIWg6C6eetWnsuZpgdzffMmwko1DnXO3G55xdbWUpscB61qbZ/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H1fHKLF6Y2AACEFyLquXiLF6Y2AACEF0xtAABIJoio9+ItXpjaAAAQXoio9+JtXpjaAAAQXoio79Ltvku3e21hagMAQHhxprYjTG0AAAgvRNR/6TYvTG0AAAgvRNT/6W1emNoAABBerKk9wAlTGwAAwgsRDWBqAwBAskBEg5/d4YWpDQAA4QVTGwAAkgkiGvrsDi9MbQAACC9ENPT5HV6Y2gAAEF6IaPjzO7wwtQEAILwQ0cjlO7wwtQEAILwQ0cjlu7wwtQEAILwQ0Z8v3+WFqQ0AAOGFiM5cucsLUxsAAMILpjYAACQTRDT6xT1emNoAABBeiGjsi3u8MLUBACC8ENHZq/d4YWoDAEB4IaJzE/d4YWoDAEB4IaJzE/d5YWoDAEB4IaLzf73PC1MbAADCCxF99Nf7vDC1AQAgtPw/iqJ/5w+GbYYAAAAASUVORK5CYII=" alt="" />

比较完之后,相信大家应该知道了这个类的大概作用了。

编写自己的Data Annotations

虽然系统已经自带了常用的验证Attribute,但是,在实际应用中,我们仍然免不了要编写自己的验证规则,首先我们来看下其结构:

可以看出,要编写一个自己的验证规则是非常简单的,只需要继承自ValidationAttribute类,并重载IsValid方法即可。一个简单的示例如下:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
publicclassCountryAttribute : ValidationAttribute
{
publicstring AllowCountry { get; set; }

publicoverridebool IsValid(object value)
{
returnstring.Equals(value, AllowCountry);
}

protectedoverrideValidationResult IsValid(object value, ValidationContext validationContext)
{
if (string.Equals(value, AllowCountry))
returnValidationResult.Success;
else
returnnewValidationResult(string.Format("{0} 字段非法", validationContext.DisplayName), new []{ validationContext.MemberName});
}
}

从上我们可以看到,IsValid是有两个版本的,我们实际上只需要重载一个即可,如果需要自定义错误信息可以用下面那个。 如果两个版本都重载了默认情况下使用下面的那个高级的版本。

更多信息:

关于Data Annotations的更多知识这里就不做介绍了,感兴趣的朋友可以参看这篇文章:DataAnnotations Validation for Beginner

WPF中的数据验证:

实际上,数据验证往往并非用于前例所示的控制台程序程序,而是用于WPF这类GUI程序中。 WPF程序中也有一套非常完善的数据验证框架值得学习一下,限于篇幅这里就不多介绍了,感兴趣的朋友可以看看这篇文章:Data validation in WPF

使用Data Annotations进行手动数据验证的更多相关文章

  1. MVC5 + EF6 + Bootstrap3 (15) 应用ModelState和Data Annotation做服务器端数据验证

    Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-server-side-validation.html 系列 ...

  2. 我这么玩Web Api(二):数据验证,全局数据验证与单元测试

    目录 一.模型状态 - ModelState 二.数据注解 - Data Annotations 三.自定义数据注解 四.全局数据验证 五.单元测试   一.模型状态 - ModelState 我理解 ...

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

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

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

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

  5. Manual Validation with Data Annotations C#对实体类进行手动验证

    Several people have asked me about using data annotations for validation outside of a UI framework, ...

  6. [MVC4]Data Annotations Extensions:无法使用EmailAddress等验证特性的解决方法

    本文地址:http://www.cnblogs.com/egger/p/3404159.html  欢迎转载 ,请保留此链接๑•́ ₃•̀๑! 数据注解(Data Annotations) Web应用 ...

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

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

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

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

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

    I.EF的默认映射 上节我们创建项目,通过定义实体类就可以自动生成数据库,并且EF帮我们自动设置了数据库的主键.外键以及表名和字段的类型等,这就是EF的默认映射.具体分为: 数据库映射:Code Fi ...

随机推荐

  1. java新手笔记34 连接数据库

    1.JdbcUtil package com.yfs.javase.jdbc; import java.sql.Connection; import java.sql.DriverManager; i ...

  2. Smarty模板引擎技术

    Smarty模板引擎技术 什么是模板引擎? 什么是Smarty模板引擎? 为何选择Smarty模板引擎? 如何使用Smarty模板引擎? 一.历史背景 场景一:回顾之前编写PHP项目的方式 //链接数 ...

  3. 引用、return

    C语言中没有引用,引用(reference)是c++对c语言的重要扩充.通俗点说,引用就是“起别名”.比如变量data,和它的引用 RefData.虽然名字不同,但是操作他们的时候,都操作的是相同的内 ...

  4. Linux C SMTP POP3 极简陋邮件客户端

    以前以为协议非常高神,但做了这个之后发现还好,没想象的那么艰难. 先要了解邮件的原理 再者就是上面2协议 可以先用telnet测试一下,以初步了解那2协议:http://hi.baidu.com/34 ...

  5. Mysql单实例脚本自动化安装

    安装包:mysql-5.6.31.tar.gz 已有配置文件:my.cnf *注意:本次Mysql的配置文件是在my.cnf的基础上更改得到的,my.cnf存放路径为/opt/rh/my.cnf 脚本 ...

  6. Spring MVC - log4j 配置

    http://blog.csdn.net/yhqbsand/article/details/8764388

  7. 如何解决NTLDR is missing

    问题:ntldr文件不见了,无法进入系统.本系统win XP 简体中文32位 解决步骤: (1)我找来一张win XP 英文版 32位的系统光盘(用U盘驱动也行) (2)重新启动计算机,并进入CMOS ...

  8. html5 的<audio> 音频 audio的“坑”

    <audio>标签是html5的一个非常有意义的特性.告别的flash的时代.它的属性有: autoplay:音频就绪后马上播放 controls:出现该属性,向用户显示播放的控件. lo ...

  9. 学习VirtualEnv和Nginx+uwsgi用于django项目部署

    以下叙述中用到的操作系统:Linux CentOS 6.X. 最近几天了解一下VirtualEnv,Apache+Daemon mode,Nginx+uwsgi的概念,并且在项目中实验性部署了一下(目 ...

  10. spring mvc 初步接触学习笔记

    1.使用maven导入spring mvc web 的jar 包 最新语句 <dependency> <groupId>org.springframework</grou ...