2016-01-06 154 views
0

如何使用jQuery.validator和使用jQuery 1.10或更高版本時執行ajax請求的規則。 jQuery 1.10不再支持async = false選項。因此,jQuery.validator規則在ajax導致成功回調到達之前結束。jQuery驗證器和jQuery使用AJAX的自定義規則1.10

這個老後(當ASYN =虛假不建議使用)表明選項的我們:jQuery validator and a custom rule that uses AJAX

我使用jQuery.validator在asp.net MVC 5.2應用

+0

你做服務器的請求做客戶端驗證?似乎對我毫無意義。驗證客戶端上的客戶端數據和服務器上的所有驗證。你的自定義驗證器是做什麼的? – heymega

+0

您可以使用遠程方法,還是僅僅使用服務器方法返回結果,您的方法還有更多嗎? http://jqueryvalidation.org/remote-method –

+0

我需要檢查輸入的電子郵件地址是否尚未使用。在輸入數據時而不是在提交表單時觸發客戶端驗證。因此用戶立即獲得反饋。我需要檢查是否可以使用遠程方法。 – rherzog

回答

1
的情況下

解決方案是將MVC標準驗證屬性[Remote]與處理這些客戶端驗證請求的控制器結合使用。

該解決方案完全基於此Microsoft article

快速求和式:使用[遠程]屬性指定控制器,並得到行動

  1. 標註您的視圖模型屬性被稱爲:

    [Required] 
    [Display(Name = "E-Mail")] 
    [EmailAddress] 
    [System.Web.Mvc.Remote("EMail_Available", "Validation")] 
    public string Email { get; set; } 
    
  2. 創建具有控制器輸出緩存禁用:

    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] 
    public class ValidationController : Controller 
    { 
        public ValidationController() {} 
    
        // GET: Validation 
        [AllowAnonymous] 
        public async Task<JsonResult> EMail_Available(string EMail) { 
    
        var user = await UserManager.FindByEmail(EMail); 
        if (user == null) 
         return Json(true, JsonRequestBehavior.AllowGet); 
    
        string suggestedUID = String.Format(CultureInfo.InvariantCulture, 
         "Die E-Mail '{0}' wurde bereits registriert.", EMail); 
    
        return Json(suggestedUID, JsonRequestBehavior.AllowGet); 
        } 
    } 
    
  3. In您的Razor視圖提供@ Html.ValidationMessageFor(...)

    <div class="form-group"> 
        @Html.LabelFor(m => m.Email, new { @class = "col-md-4 control-label" }) 
        <div class="col-md-8 input-group"> 
         <span class="input-group-addon colorLogin"><span class="glyphicon glyphicon-envelope" id="spaces"></span></span> 
         @Html.TextBoxFor(m => m.Email, new { @id = "register_email", @class = "form-control", @placeholder = "E-Mail", @autofocus = "" }) 
         @Html.ValidationMessageFor(m => m.Email, "", new { @id = "register_email_error", @class = "text-danger" }, "div") 
        </div> 
    </div>