我有一个简单的表单验证脚本,它遍历我的输入,检查 ID 是否在数组中,如果是,则验证框中是否输入了某些内容。但是由于某种原因,代码的 .each 部分正在破坏它。
我的代码:
function ValForm() {
var validate = ['name', 'addr1', 'city', 'county', 'pcode'];
var regpcode = '/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/i';
var fail = false;
$('#summary-wrap input').each(function() {
var id = $(this).attr('id');
if($.inArray(id, validate)) {
if(id == 'pcode' && !regpcode.test(this.value)) {
fail = true;
} else if(this.value.length < 2) {
fail = true;
}
}
});
if(fail) {
alert('Please complete all required fields before continuing.');
$(this).focus();
return false;
}
return true;
}
如果我输入无效数据,表单仍然会提交。即使我设置了fail = true,或者将所有返回值都设置为false,表单仍然提交。这是我的表格:
<form name="delivery" action="knee-icepack.php" method="post" onsubmit="return ValForm();">
<label for="name">Name <span class="req">*</span>:</label><input type="text" name="name" id="name" required="required" />
<br clear="all" />
<label for="addr1">Address Line 1 <span class="req">*</span>:</label><input type="text" name="addr1" id="addr1" required="required" />
<br clear="all" />
<label for="addr2">Address Line 2:</label><input type="text" name="addr2" id="addr2" />
<br clear="all" />
<label for="city">Town / City <span class="req">*</span>:</label><input type="text" name="city" id="city" required="required" />
<br clear="all" />
<label for="county">County <span class="req">*</span>:</label><input type="text" name="county" id="county" required="required" />
<br clear="all" />
<label for="pcode">Post Code <span class="req">*</span>:</label><input type="text" name="pcode" id="pcode" required="required" />
<br clear="all" />
<input type="submit" id="submit" value="Proceed to Payment" />
<input type="hidden" name="deliveryDetailsSubmitted" value="1" />
<img src="images/paypal.jpg" align="right" />
<br clear="all" />
<span class="small"><span class="req">*</span> required field.</span>
</form>
但是,如果我从 ValForm 函数中删除 .each 循环,它会在我设置 fail = true 时停止提交表单。我可以在循环中没有代码,它仍然无法工作。到底是怎么回事?这一直让我发疯。