MVC 数据验证

一、Required

必填选项,当提交的表单缺少该值就引发验证错误。

二、StringLength

指定字符长度

[StringLength(20)]  //字符长度不超过20个字符

[StringLength(20,MinimumLength=3)] //字符长度范围 3-20

三、RegularExpression

正则表达式验证

[RegularExpression(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", ErrorMessage = "请输入正确的电子邮箱地址!")]

四、Range

指定数值类型的最大值和最小值

[Range(35,44)] //整型,最小35,最大44
[Range(typeof(decimal),"0.00","49.99")] //decimal类型

五、Remote

利用服务器端的回调函数执行客户端的验证逻辑

需要引用命名空间:System.Web.Mvc;

[Remote("CheckUserName", "SysUser", ErrorMessage = "*该用户名已经被注册  //SysUser类名称
public string UserName
{
   get;
   set;
}

Controller代码

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] //清除缓存
public JsonResult CheckUserName(string UserName)
{
   bool result = true;
   if (UserName == "admin")
   {
     result = false;
   }
   return Json(result, JsonRequestBehavior.AllowGet);
}

六、Compare

用于确保模板对象的两个对象拥有相同的值

[DisplayName("密码")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "密码必须填写")]
[StringLength(20, MinimumLength = 3)]
public string Password { get; set; }

[DisplayName("确认密码")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "确认密码必须填写")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "两次密码不一致!")]  //添加命名空间引用报错,目前只能这么用,不清楚原因
public string ConfirmPassword { get; set; }

View->Web.Config-> <appSettings>中加入

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>





猜你喜欢

转载自blog.csdn.net/oYuHuaChen/article/details/72833232
今日推荐