数据校验是网站开发不可取少点部分,而MVC在这方面给我们提供了很多集成好了的validationattribute在程序集System.ComponentModel.DataAnnotations里面(MVC验证可以实现双向验证,server-side and client-side):
- Remote:用服务器端回调函数执行客户端的验证逻辑
- Required:必填选项 : [Required(ErrorMessage="{0}不能为空!")]
- RegularExpression:正则表达式需要匹配的字符串: [RegularExpression(@"^w+@[a-zA-Z_]+?.[a-zA-Z]{2,3}$", ErrorMessage = "请输入正确的电子邮箱地址!")]
- Range:数值类型值的最小值和最大值[Range(typeof(decimal),"0.00","49.99")]
- StringLength:指定允许的长度[StringLength(20)] [StringLength(20,MinimumLength=3)] 最大不能超过最小不能低于多少个字符
- Compare:模板对象的两个对象拥有相同的值 [Compare("NewPassWord")]
同时也可以自定义开发时候需要进行的一些特殊的验证,需要继承ValidationAttribute,重写IsVaild方法。
Remote Demo:注册时候用来验证数据库是否已经存在相同的用户名
Model: public class User { [ScaffoldColumn(false)] public int id { get; set; } [Display(Name = "姓名")] [Remote("MutipleNameChecking", "Validation", ErrorMessage = "用户名已经存在!")] //参数1参数2分别代表要回调的action和controller [Required(ErrorMessage="{0}不能为空")] public string name { get; set; } [Display(Name="密码")] [Required(ErrorMessage="不能为空")] [DataType(DataType.Password)] [RegularExpression("^[0-9]*",ErrorMessage="必须为数字")] public string pass { get; set; } [Display(Name = "性别")] public bool sex { get; set; } [Display(Name = "出生日期")] [DataType(DataType.Date)] public DateTime birthday { get; set; } } client: @using (Html.BeginForm()) { @Html.LabelFor(m => m.name) @Html.EditorFor(m => m.name) @Html.ValidationMessageFor(m=>m.name) <br /> @Html.LabelFor(m => m.pass) @Html.EditorFor(m => m.pass) @Html.ValidationMessageFor(m => m.pass) <br /> @Html.LabelFor(m => m.birthday) @Html.EditorFor(m => m.birthday) @Html.ValidationMessageFor(m => m.birthday) <input type="submit" id ="login" value="登录" /> } Cotroller: public JsonResult MutipleNameChecking(string name)//name参数要和Model保持一致 { List<User> user = new List<User>(); user.Add(new User() { name="lina" }); bool IsExist = user.Where(u => u.name == name).Count() > 0; return Json(!IsExist,JsonRequestBehavior.AllowGet);//存在用户名返回false }