MVC4数据注解和验证

model中的验证注解特性:

public class StuInfo
    {
        public int ID { get; set;}
 
        [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","StuInfo", ErrorMessage = "{0}已被注册")]   //在指定的Conteroller中的通道(route)中验证数据
        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;}
}

远程验证的通道:

public JsonResult CheckPhone(string phone)
              {
                var result= StuInfoBll.FindPhone(phone).count == 0;
                return Json(result, JsonRequestBehavior.AllowGet);
          }

效果: 
    正常下的网页:

必须字段验证效果:

值范围、值类型验证效果:

正则验证和比较字段值效果:

数据类型验证效果:

posted @ 2015-01-19 08:43  赤狐(zcm123)  阅读(184)  评论(0编辑  收藏  举报