2016-01-06 91 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>