[Display(Name = "姓名")] //设置要显示的字段名
[Required(ErrorMessage = "您需要填写{0}")] //设置为必须字段 错误提示
[StringLength(50, MinimumLength = 3)] //设置长度和最小长度
public string Name { get; set; }
[Display(Name = "年龄")]
[Range(1, 150, ErrorMessage = "年龄填写不正确!")] //设置 值范围
public int Age { get; set; }
[Display(Name = "身高")]
[Range(typeof(decimal), "50.00", "250.00", ErrorMessage = "身高超出指定范围")]
public decimal Height { get; set; }
[Display(Name = "生日")]
[DataType(DataType.Date, ErrorMessage = "{0}格式不正确")] //设置数据类型以及错误提示
public DateTime Birthday { get; set; }
[Display(Name = "电话")]
[Remote("CheckPhone", "Account", ErrorMessage = "{0}已被注册")] //使用ajax在指定的AccountConteroller中的CheckPhone方法中验证数据
public string Phone { get; set; }
[Display(Name = "地址")]
[DataType(DataType.MultilineText)]
public string Address { get; set; }
[Display(Name = "电子邮箱")]
[RegularExpression(@"(\w)+(\.\w+)*@(\w)+((\.\w+)+)", ErrorMessage = "{0}格式不正确")] //正则验证
public string Email { get; set; }
[Display(Name = "再次输入电子邮箱")]
[Compare("Email", ErrorMessage = "{0}两次输入不一致")] //设置比较两个字段的值
public string EmailConfirm { get; set; }
[Display(Name = "密码")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "备用电子邮箱")]
[DataType(DataType.EmailAddress, ErrorMessage = "{0}格式不正确")]
public string email_B { get; set; }
}
ErrorMessage允许开发者使用{0}占位符来显示字段的显示名(即[Display(Name = "用户名")]),如果没有Display特性,那么会显示属性名。如:
[Required(ErrorMessage = "{0}不能为空!")]
[Display(Name = "用户名")]
public string UserName { get; set; }
如果验证的特性中还有其他参数,那么ErrorMessage可以用占位符直接显示其他参数,如:
[Required]
[StringLength(100, ErrorMessage = "请输入{2}到{1}位的{0}。", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Password { get; set; }
//系统会提示:“请输入6到100位的密码”。