【问题标题】:jQuery validator and a custom rule that uses AJAX with jQuery 1.10jQuery 验证器和使用 AJAX 和 jQuery 1.10 的自定义规则
【发布时间】:2016-04-10 20:55:27
【问题描述】:

当使用 jQuery 1.10 或更高版本时,如何将 JQuery.validator 与执行 ajax 请求的规则一起使用。 jQuery 1.10 不再支持 async = false 选项。因此,jQuery.validator 规则在成功回调中的 ajax 结果到达之前完成。

这篇旧帖子(未弃用 asyn=false 时)向我们建议了该选项:jQuery validator and a custom rule that uses AJAX

我在 asp.net MVC 5.2 应用程序的上下文中使用 jQuery.validator

【问题讨论】:

  • 您是否通过向服务器发出请求来进行客户端验证?对我来说似乎有点毫无意义。验证客户端上的客户端数据和服务器上的所有验证。你的自定义验证器是做什么的?
  • 您可以使用远程方法还是您的方法不仅仅是让服务器方法返回结果? jqueryvalidation.org/remote-method
  • 我需要检查输入的E-Mail地址是否未被使用。客户端验证在输入数据时触发,而不是在提交表单时触发。因此,用户立即得到反馈。我需要检查是否可以使用远程方法。
  • 我们在那个确切的场景中使用远程方法(检查输入的电子邮件是否在使用中,一旦他们从电子邮件字段中跳出)。但是,我们不使用不显眼的验证,因此它可能会根据您的使用情况而有所不同。
  • 我想要一个自定义的 ValidationAttribute 并像 ViewModel 上的内置属性一样使用它,例如[必需] 或 [电子邮件地址]。 stephen.vakil 您是在谈论here 中描述的 [Remote] 属性吗?无论如何,[Remote] 属性可以按我的需要工作!谢谢!

标签: jquery ajax asp.net-mvc validation


【解决方案1】:

解决方案是将 MVC 标准验证属性 [Remote] 与处理这些客户端验证请求的控制器结合使用。

解决方案完全基于这个Microsoft article

快速总结:

  1. 使用指定控制器的 [Remote] 属性注释您的 ViewModel 属性并获取要调用的操作:

    [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. 在您的 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>
    

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2018-03-02
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多