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

时间:2016-01-06 22:54:10

标签: jquery jquery-validate

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();  
});

1 个答案:

答案 0 :(得分:1)

根据文档,默认情况下,验证是“懒惰”。

  

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事件中得到验证。

DEMO:http://jsfiddle.net/yo4y9s64/

请参阅this answer以实施“Eager”验证...

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

DEMO 2:http://jsfiddle.net/yo4y9s64/1/