问题:
<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();
});
答案 0 :(得分:1)
根据文档,默认情况下,验证是“懒惰”。
这意味着只需加载表单并删除值即可。您必须清除该值并单击“提交”按钮以触发验证。然后,所有后续互动都会在keyup
和focusout
事件中得到验证。
DEMO:http://jsfiddle.net/yo4y9s64/
请参阅this answer以实施“Eager”验证...
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
}