[英]JQuery: validate all inputs within a form
I need to apply same jquery validate rule to all the inputs with the name="time"
of a table within a form. 我需要将相同的jquery验证规则应用于表格中表
name="time"
的所有输入。 Html code: HTML代码:
<form id="thresholds">
<table id="table" width="100%">
<thead>
<tr>
<th width="35%">Service Name</th>
<th width="65%">Threshold</th>
</tr>
</thead>
<tbody>
<tr>
<td>Srv1</td>
<td><input id="Srv1" name="time"></input></td>
</tr>
<tr>
<td>Srv2</td>
<td><input id="Srv2" name="time"></input></td>
</tr>
<tr>
<td>Srv3</td>
<td><input id="Srv3" name="time"></input></td>
</tr>
</tbody>
</table>
</form>
All the values in the inputs are expected to be valid timestamps. 输入中的所有值均应为有效时间戳。 The method is
方法是
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#thresholds").validate({
rules: {
time: {
required: true,
time: true
}
}
});
This way the rule evaluates only the first input "Srv1". 这样,规则仅评估第一个输入“ Srv1”。
I need it to affect Srv2 and Srv3 as well, ie all the 我也需要它来影响Srv2和Srv3,即所有
$('input[name="time"]').
Thanks in advance for your help. 在此先感谢您的帮助。
The problem was not in validator or selector. 问题不在验证器或选择器中。 They are both correct.
他们都是正确的。 In further lines of the code I tried to enable/disable the Submit button relying on the form state:
在代码的其他几行中,我尝试依赖于表单状态启用/禁用Submit按钮:
$('input[name="time"]').on('keyup blur', function () {
if ($('#thresholds').valid()) {
$('#run').prop('disabled', false);
} else {
$('#run').prop('disabled', true);
}
});
For some reason the condition $('#thresholds').valid() always returned TRUE even for invalid or empty input. 由于某些原因,条件$('#thresholds')。valid()始终返回TRUE,即使输入无效或为空。 The validation seemed to not work as well.
验证似乎效果不佳。
Validating each input individually solved the problem: 分别验证每个输入可解决问题:
$('input[name="time"]').on('keyup blur', function () {
if ($('#thresholds').validate().element($(this))) {
$('#run').prop('disabled', false);
} else {
$('#run').prop('disabled', true);
}
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.