Asp.Net MVC 使用 DataAnnotations 进行模型验证

通过为模型类增加数据描述的 DataAnnotations ,我们可以容易地为应用程序增加验证的功能。DataAnnotations 允许我们描述希望应用在模型属性上的验证规则,ASP.NET MVC 将会使用这些 DataAnnotations ,然后将适当的验证信息返回给用户。

常用的 DataAnnotations 包括:

  1. Required 必须 – 表示这个属性是必须提供内容的字段
  2. DisplayName 显示名 – 定义表单字段的提示名称
  3. StringLength 字符串长度 – 定义字符串类型的属性的最大长度
  4. Range 范围 – 为数字类型的属性提供最大值和最小值
  5. Bind 绑定 – 列出在将请求参数绑定到模型的时候,包含和不包含的字段
  6. ScaffoldColumn 支架列 - 在编辑表单的时候,需要隐藏起来的的字符
  7. Compare 比较 - 与制定的字段值进行比较 具体见代码
using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

namespace SKUOrderMVC.Models
{
    public class ChangePassword
    {
        [Required]
        [Display(Name = "Email")]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(32, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

    }
}

当然还有其他的一些属性,比如正则表达式等,不用辅助编码就可以完成对数据输入格式的验证。

posted on 2017-04-06 23:06  XM-Zhangjh  阅读(254)  评论(0编辑  收藏  举报