1.Mvc自带的校验
新建一个用户实体类
public class Users { public int Id { get; set; } [StringLength(5,ErrorMessage = "*长度必须<5")] [Required(ErrorMessage = "*姓名必填")] public string UserName { get; set; } [RegularExpression(@"^d+$")] [Range(18,100)] [Required(ErrorMessage = "*")] public int Age{get; set; } }
新建控制器users和创建强制类型视图,并带create模版
public ActionResult Index() { return View(); } public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(User user) { if (ModelState.IsValid) { //ModelState.IsValid为true校验成功 } return RedirectToAction("Index"); }
前台页面View需要这3个js的支持
<script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
2.全局客户端(服务端)校验开启或关闭
在web.config配置
<appSettings> <add key="webpages:Enabled" value="false" /> <add key="EnableClientValidation" value="true" />//全局客户端校验开启 <add key="EnableUnobtrusiveJavaScript" value="true" />//全局服务端校验开启 </appSettings>
在某个页面里
@{ Html.EnableClientValidation(false);//当前页面客户端验证关闭 Html.EnableUnobtrusiveJavaScript(false);//当前服务端验证关闭 }