jquery 当输入带有来自服务器的值时,验证插件不验证

jquery validation plugin does not validate when input comes with values from server

jsbin

问题:

<input id="cname" name="name" minlength="2" type="text" required value="test">

带有给定值 test。现在删除值时,不会触发验证插件。

html

<!DOCTYPE html>
<html>
<head>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>


  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Name comes with value, when value removed, no error shows!</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required value="test">
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" value="" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>

    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form> 
</body>
</html>

JS

$(function(){
  $("#commentForm").validate();  
});

根据文档,默认情况下,验证是 "Lazy"。

Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value

这意味着简单地加载一个表单并删除一个值将无济于事。您必须清除该值并单击提交按钮以触发验证。然后在 keyupfocusout 事件上验证所有后续交互。

演示:http://jsfiddle.net/yo4y9s64/


参考this answer实现"Eager"验证...

onkeyup: function (element, event) {
    if (event.which === 9 && this.elementValue(element) === "") {
        return;
    } else {
        this.element(element);
    }
}

演示 2:http://jsfiddle.net/yo4y9s64/1/