【发布时间】:2012-05-01 21:16:07
【问题描述】:
我正在制作一个需要填写至少一个字段并且所有输入必须是整数或小数的表单。我正在使用 jquery 的验证插件进行验证。我已经修改了我发现here 的东西,这似乎部分起到了作用。现在我有:
<SCRIPT>
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var validOrNot = $(selector, element.form).filter(function() {
// Each field is kept if it has a value
return $(this).val();
// Set to true if there are enough, else to false
}).length >= numberRequired;
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
fields.valid();
fields.data('being_validated', false);
}
return validOrNot;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
$(document).ready(function(){
var container = $('#errorContainer');
$("#FORMMM").validate( {
rules: {
groceries: {digits: true,require_from_group: [1,".at_least_one"]},
gas: {digits: true,require_from_group: [1,".at_least_one"]},
hotels: {digits: true,require_from_group: [1,".at_least_one"]}
},
success: function(label) {
label.html(" ").addClass("checked");
},
errorContainer: container,
errorLabelContainer: $("ol", container),
wrapper: 'li',
meta: "validate"
});
});
</SCRIPT>
HTML 如下,在我的实际表单中,有 15 个输入字段,我只是在这里压缩它:
<form action="results.php" target="_blank" id="FORMMM">
<div style="clear:both">
<label for="groceries">Groceries</label>
<div style="float:right">
$<input name="groceries" type="text" class="at_least_one idleField"></div>
</div>
<div style="clear:both">
<label for="gas">Gas</label>
<div style="float:right">
$<input name="gas" type="text" class="at_least_one idleField">
</div>
</div>
<div style="clear:both">
<label for="hotels">Hotels</label>
<div style="float:right">
$<input name="hotels" type="text" class="at_least_one idleField">
</div>
</div>
<div id="button">
<input name="" type="submit" value="Calculate" class="calc_button" style="cursor:hand">
</div>
</form>
<div id="errorContainer">
<h4>errors</h4>
<ol>
</ol>
</div>
目前验证存在两个问题。如果所有字段都留空,当我只需要一个时,我会收到 3 条错误消息!
另外,如果我在其中一个输入中输入一个字母,我会得到一秒钟的“仅限数字”错误消息,但表单仍然提交,因为至少填写 1 个字段的第二次测试弥补了因为没有数字。
我这样做是否完全错误?我在这里或 jquery 论坛上找不到的示例似乎都不完全适合。我应该从哪个方向解决这个问题?
【问题讨论】:
-
为了 Web 开发中的一切神圣,请在您的表单中使用
<label for="input-id-name">;它使表单更易于访问和用户友好。 -
哦,我会这样做,这是一个很好的点,我只是想让 js 先工作,然后我想我会设置标签、占位符等。
-
别担心,我也没有使用这些丑陋的表格,我现在只是这样写的,一旦我弄清楚如何让错误显示出来,我打算修复它。
-
你应该奖励其中一个答案。
标签: javascript jquery validation input