我有一个类似于以下代码的html表单。我的问题是我想基于多个标准进行验证...数字可以是0或者它必须大于700.我使用数组作为输入名称,这使得我很难获得javascript解决方案工作。在这种情况下如何使用多个critera进行验证?
<form name="endingweights" method="post">
<input type="hidden" value="1" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
<input type="hidden" value="2" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
<input type="hidden" value="3" name="strain[]"></td><td><input type="number" step="any" name="ending[]" min="0" max="1500" required />
答案 0 :(得分:1)
使用以下javascript函数进行验证。
<script>
function validateForm() {
var x = document.forms["endingweights"].elements["ending[]"];
for (var i = 0; i < x.length; i++) {
var aControl = x[i].value;
if (aControl>0 && aControl<700) {
alert("Incorrect Weight, must be 0 or greater than 700.");
x[i].focus();
return false;
}
}}
</script>
答案 1 :(得分:1)
如果您为输入分配id
,则可以更轻松地通过javascript验证。这样,您可以在提交表单时检查输入的值。
<强> HTML:强>
<form name="endingweights" method="post">
<!-- hidden inputs -->
<input id="foo" type="number" min="0" max="1500" required>
<input id="bar" type="number" min="0" max="1500" required>
<input id="baz" type="number" min="0" max="1500" required>
<input type="submit" value="Submit">
</form>
<强> JS:强>
var form = document.forms['endingweights'],
foo = document.getElementById('foo'),
bar = document.getElementById('bar'),
baz = document.getElementById('baz');
// validate inputs and form
form.addEventListener('submit', function(ev) {
// stop this from auto submitting
ev.preventDefault();
ev.stopPropagation();
// make sure constraints are followed
if ((foo.value !== 0 && foo.value <= 700) ||
(bar.value !== 0 && bar.value <= 700) ||
(baz.value !== 0 && baz.value <= 700))
{
alert("All input values must be either 0 or greater than 700");
return false;
}
// perform other validations if necessary
// submit form
form.submit();
}, false);
演示jsfiddle!
name
属性在处理提交的数据时在服务器端最有用,但id
在处理客户端验证时效果最佳。