rherzog
rherzog

Reputation: 71

jQuery validator and a custom rule that uses AJAX with jQuery 1.10

How can the JQuery.validator be used with rules that do ajax requests when jQuery 1.10 or greater is used. jQuery 1.10 doesn't support the async = false option anymore. Hence the jQuery.validator rule finishes before the ajax result in the success-callback arrives.

This old post (when asyn=false wasn't deprecated) suggests the us of that option: jQuery validator and a custom rule that uses AJAX

I am using the jQuery.validator in the context of a asp.net MVC 5.2 application

Upvotes: 0

Views: 347

Answers (1)

rherzog
rherzog

Reputation: 71

The solution is to use the MVC standard validation attribute [Remote] in combination with a conroller that handles those client-side validation requests.

The solution is entirely based on this Microsoft article.

A quick sum-up:

  1. Annotate your ViewModel property with the [Remote] attribute specifying the controller and get action to be called:

    [Required]
    [Display(Name = "E-Mail")]
    [EmailAddress]
    [System.Web.Mvc.Remote("EMail_Available", "Validation")]
    public string Email { get; set; }
    
  2. Create a Controller which has output-caching disabled:

    [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 your Razor view provide a @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>
    

Upvotes: 1

Related Questions