我整天都在努力解决JQuery验证问题。仅在其中验证第一个字段的地方。
我设法在这里复制它:
$(document).ready(function() {
$('#go').click(function() {
console.log('go clicked');
if ($('#detailsForm').valid()) {
alert('if you see this then the form is valid.');
}
});
});
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@1.10.0" data-semver="1.10.0" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script data-require="jquery-validate@1.10.0" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.js"></script>
<script data-require="jquery-validate@1.10.0" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/additional-methods.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>This doesn't work :(</h1>
<form id="detailsForm">
<div class="row guttered-bottom">
<div class="col-md-6 col-xs-12">
<div class="row">
<div class="col-md-12 col-xs-12">
<br />
First Name<div style="color:#E320C9">*</div>
<div class="input-container">
<input id="ReserveFirstName" type="text" class="input-large input-wide" placeholder="Enter your first name" required="true" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12">
<br />
Last Name<div style="color:#E320C9">*</div>
<div class="input-container">
<input id="ReserveLastName" type="text" class="input-large input-wide" placeholder="Enter your last name" required="true" />
</div>
</div>
</div>
</div>
</div>
</form>
<br>
<button id="go">CLICK ME! </button>
</body>
</html>
重现步骤:单击按钮,然后观察到第一个字段(名字)的验证消息。输入名字,然后再次单击按钮。请注意,即使两个字段都是必需的,该表单似乎仍在验证。
我在做什么错?
答案 0 :(得分:2)
jQuery Validate需要每个输入都具有一个name
属性。否则,它将无法正确创建用于存储验证结果的输入对象。
只需为每个输入添加一个唯一的名称,您就应该很好:
<input name="ReserveFirstName" id="ReserveFirstName" type="text" class="input-large input-wide" placeholder="Enter your first name" required="true" />
<input name="ReserveLastName" id="ReserveLastName" type="text" class="input-large input-wide" placeholder="Enter your last name" required="true" />
答案 1 :(得分:-3)
有效值从表单中返回一个布尔值,但必须在onClick事件之前之前使用它。
var form = $( "#myform" );
form.validate();
$( "button" ).click(function() {
alert( "Valid: " + form.valid() );
});
您可以在源代码上自己尝试一下:https://jqueryvalidation.org/valid/