本文體驗MVC服務端和客戶端驗證。主要涉及:
※ 基礎驗證
※ 遠程驗證1個或多個屬性及注意點jquery
基礎體驗app
建立MVC4的Internet項目,自己包含了基本的Model,Views,Controller.異步
□ Model打上驗證特性ui

展開 public class RegisterModel
{
[Required]
[StringLength(3, MinimumLength = 2)] //加
[Display(Name = "用戶名")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0}欄位最少{2}個字,最多{1}個字", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密碼")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "確認密碼")]
[Compare("Password", ErrorMessage = "密碼和確認密碼不匹配。")]
public string ConfirmPassword { get; set; }
}
□ HomeController中關於註冊的部分this

展開 [AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// 嘗試註冊用戶
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// 若是咱們進行到這一步時某個地方出錯,則從新顯示錶單
return View(model);
}
□ /Home/Register視圖spa

展開@model MvcValidation.Models.RegisterModel
@{
ViewBag.Title = "註冊";
}
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<fieldset>
<legend>註冊表單</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
</ol>
<input type="submit" value="註冊" />
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
效果:
code
□ 去除客戶端驗證orm
<appSettings>
<add key="ClientValidationEnabled" value="false" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>blog
把與客戶端驗證相關的屬性設置爲false,發現驗證慢了不少。ip
體驗遠程驗證屬性
有時候,好比驗證用戶名是否存在,咱們但願能夠發一個異步請求到控制器。
給屬性打上Remote屬性。

展開 public class RegisterModel
{
[Required]
[StringLength(6, MinimumLength = 2)] //加
[Display(Name = "用戶名")]
[Remote("CheckUserName","Validate", ErrorMessage = "遠程驗證用戶名失敗")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "{0}欄位最少{2}個字,最多{1}個字", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "密碼")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "確認密碼")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "密碼和確認密碼不匹配。")]
public string ConfirmPassword { get; set; }
}
Validate控制器

展開 //這裏的參數userName必須和view model中的屬性UserName保持一致
public JsonResult CheckUserName(string userName)
{
bool isValidate = false;
//假設讓某個username不經過
if (userName != "demo")
{
isValidate = true;
}
//Remote驗證是經過get方式請求的
return Json(isValidate, JsonRequestBehavior.AllowGet);
}
注意:
遠程驗證控制器方法參數必須和view model中須要遠程驗證的屬性一致,但不區分大小寫。
結果:

□ 同時遠程驗證多個屬性
好比咱們想同時遠程驗證UserName和Email。
咱們能夠在View model的其中一個屬性打上Remote,其它須要Remote驗證的屬性放在AdditionalFields中列舉。
public string UserName { get; set; }
[Remote("CheckUserName", "Validate", AdditionalFields = "UserName", ErrorMessage = "遠端驗證失敗")]
public string Email { get; set; }
注意:
AdditionalFields列舉的字段是區分大小寫的。
對應控制器遠程驗證方法:

展開 //這裏的參數userName,email必須和view model中的屬性UserName, Email保持一致,不區分大小寫
public JsonResult CheckUserName(string userName, string email)
{
bool isValidate = false;
//假設讓某個username不經過
if (userName != "demo" && email != "abc@qq.com" )
{
isValidate = true;
}
//Remote驗證是經過get方式請求的
return Json(isValidate, JsonRequestBehavior.AllowGet);
}