ASP.NET MVC5(四):数据注解和验证
前言 用户输入验证的工作,不仅要在客户端浏览器中执行,还要在服务端执行。主要原因是客户端验证会对输入数据给出即时反馈,提高用户体验;服务器端验证,主要是因为不能完全信任用户提供的数据。ASP.NET MVC框架提供了强大的验证组件帮助我们处理这些繁杂的问题。 数据验证 验证注解的使用 验证注解特性定义在命名空间System.ComponentModel.DataAnnotations中,它们提供了服务器端验证的功能,当在模型的属性上使用时,框架也支持客户端验证。常用特性简介: Required 当属性值为null或者空时,将引发一个验证错误,可以理解为若添加了Required特性,则此项为必填项。 StringLength 限定字符串长度。 RegularExpression 使用正则表达式验证输入的字符串是否符合格式要求。 Range 用来指定输入数值来的最小值和最大值。 Compare 用来判断两个属性是否拥有相同的值。例如,确保两次输入的密码相同。 Remote 利用服务器端的回调函数执行客户端的逻辑验证。 下面,通过一个简单的示例来讲解这些特性的使用方法。 假设现在我们开发一套图书管理系统,在Models文件夹中创建Book类,用来保存书籍的基本信息。 public class Book { public int Id { get; set; } public