JQuery Validation Plugin: Use remote with delay
<p>I am using the <a href="https://jqueryvalidation.org/remote-method/" rel="nofollow">remote method</a> from the <a href="https://jqueryvalidation.org/" rel="nofollow">jQuery validation plugin</a> which makes an ajax call. The remote function is activated each time a key is pressed in the input field. I would like to add a delay, so that the ajax request is only trigged when the user stopped pressing a key for some miliseconds.</p>

<p>This problem was posed in 2012 <a href="https://github.com/jzaefferer/jquery-validation/issues/466" rel="nofollow">at GitHub</a> but was closed by the developer in 2015:</p>

<blockquote>
  <p>I'm sorry for the lack of activity on this issue. Instead of leaving
  it open any longer, I decided to close old issues without trying to
  address them, to longer give the false impression that it will get
  addressed eventually.</p>
</blockquote>

<p>In the discussion forum, the user lohfu proposed the following solution:</p>

<pre><code>$.validator.methods._remote = $.validator.methods.remote;

var timer = 0;
$.validator.methods.remote = function () {
    clearTimeout(timer);

    var args = arguments;

    timer = setTimeout(function() {
        $.validator.methods._remote.apply(this, args);
    }.bind(this), 500);

    return "pending";
};
</code></pre>

<p>However, there are two main problems:</p>

<ol>
<li><p>It does not work. If I add the delay and the remote function returns false, then the form gets still submitted. </p></li>
<li><p>When I enter something in the input filed which causes an error by the remote function it correctly gets <code>class="error"</code> assigned. If I now select a different input, the <code>class="error"</code> switches to <code>class="valid"</code>, although the error message is still present and the error message is still shown. The same happens when I press submit.</p></li>
</ol>

<hr>

<p>Here is a minimal example:</p>

<p>HTML</p>

<pre><code>&lt;form action="test.php" method= "POST" id="form"&gt;
    Name:  &lt;input type="text" name="name"&gt;&lt;br&gt;
    Email:  &lt;input type="email" name="email"&gt;&lt;br&gt;
    &lt;input type="submit"&gt;
&lt;/form&gt;
</code></pre>

<p>JS     </p>

<pre><code>    $("#form").validate({
     rules: {
       name: "required",
       email: {
         required: true,
         email: true,
         remote: {
           url: "ajax.php",
           type: "post"
         }
       }
     },
     messages: {
       email: {
         remote: "Email already exists"
       }
     }
   });
</code></pre>

<p>ajax.php</p>

<pre><code>&lt;?php
header('Content-Type: application/json');

$valid = null;

echo json_encode($valid);
</code></pre>

<p>This form should never be submitted, because the ajax.php always returns false. However, entering a name and a valid email will submit the form, despite the fact that the error "Email already exists" is shown.</p>