MVC 中的远程验证
- 模型类必须有一个命名空间“System.Web.Mvc”,您已在其中定义了该属性。
using System.Web.Mvc;
[Required(ErrorMessage = "E-mail is required")]
[RegularExpression(@"^[a-zA-Z0-9_\.-]+@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Email is not valid")]
[StringLength(30, ErrorMessage = "Email must not be more than 30 char")]
[Remote("IsEmailAvailable", "User", ErrorMessage = "E-mail already in use")]
public string Email { get; set; }
- 确保您必须在控制器上实现 IsEmailAvailable Action。
[HttpGet]
public JsonResult IsEmailAvailable(string email)
{
// Check if the e-mail already exists
return Json(!db.Users.Any(x => x.Email == email), JsonRequestBehavior.AllowGet);
}
- 确保您已在 View 上添加此 js 以进行客户端验证。
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
并从 web.config 启用客户端验证
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
笔记:
远程属性仅在启用 JavaScript 时有效。如果最终用户在他/她的机器上禁用 JavaScript,则验证不起作用。这是因为 RemoteAttribute 需要 JavaScript 对服务器端验证方法进行异步 AJAX 调用。因此,用户将能够提交表单,绕过验证。这就是为什么进行服务器端验证总是很重要的原因。
如果禁用 Javascript:
为了使服务器端验证工作,当 JavaScript 被禁用时,有两种方法
- 在控制器操作方法中动态添加模型验证错误。
- 创建自定义远程属性并覆盖 IsValid() 方法。
在控制器操作方法中动态添加模型验证错误。修改用 [HttpPost] 属性修饰的 Create action 方法,如下所示。
[HttpPost]
public ActionResult Create(User user)
{
// Check if the Email already exists, and if it does, add Model validation error
if (db.Users.Any(x => x.Email == user.Email))
{
ModelState.AddModelError("Email", "Email already in use");
}
if (ModelState.IsValid)
{
db.Users.AddObject(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
此时,在浏览器中禁用 JavaScript,并测试您的应用程序。请注意,我们没有得到客户端验证,但是当您提交表单时,如果出现验证错误,服务器端验证仍然会阻止用户提交表单。
但是,将执行验证的责任委托给控制器操作方法违反了 MVC 中的关注点分离。理想情况下,所有验证逻辑都应该在模型中。在 MVC 模型中使用验证属性应该是首选的验证方法。