名称:
电子邮件:
密码:
var invalid = 0;
function validation() {
invalid = 0;
if (document.getElementById("name").value == "")
{
document.getElementById("invalid_1").innerHTMl = "you must type your name";
invalid += 1;
}
else
{
document.getElementById("invalid_1").innerHTMl = "";
}
if (invalid != 0)
{
return false;
}
else
{
return true;
}
}
我使用此代码验证我的字段,但此代码尚未运行。怎么了?
答案 0 :(得分:2)
你得到了错字。放innerHTML
而不是innerHTMl
答案 1 :(得分:2)
你应该使用innerHTML而不是innerHTMl(L也是大写)。 而不是提交onsubmit形成,使用onclick提交按钮
function validation() {
if (document.getElementById("name").value.length == 0) {
document.getElementById("invalid_1").innerHTML =
"you must type your name";
return false;
}
else {
document.getElementById("invalid_1").innerHTML = "";
return true;
}
}

<form name="survey" method="post">
<fieldset> Name: <input type="text" size="20" id="name"> <br />
Email: <input type="text" size="20" id="email"> <br />
Password: <input type="password" size="16" id="password">
<br /> <br />
<input type="submit" onclick="return validation()"
value="submit">
<input type="reset" name="reset">
<br /> <br />
</fieldset>
</form>
<p id="invalid_1"></p>
&#13;
答案 2 :(得分:1)
验证字段有几种好方法。我建议不要尝试创建轮子但使用已经实现的东西。 我告诉你Parsley library。是为验证字段和表单创建的库。
从他们的演示网站:
- 在输入上验证一个组 -
<h4>Correctly fill at least one of these blocks</h4>
<form class="demo-form">
<div data-parsley-check-children="2" data-parsley-validate-if-empty="">
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" class="form-control" name="firstname" data-parsley-length="[4, 20]" data-parsley-group="block-1">
<label for="lastname">Lastname:</label>
<input type="text" class="form-control" name="lastname" data-parsley-length="[4, 20]" data-parsley-group="block-1">
</div>
<hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" class="form-control" name="fullname" data-parsley-length="[8, 40]" data-parsley-group="block-2">
</div>
</div>
<input type="submit" class="btn btn-default validate">
</form>
<script type="text/javascript">
$(function () {
Parsley.addValidator('checkChildren', {
messages: {en: 'You must correctly fill at least one of these blocks!'},
requirementType: 'integer',
validate: function(_value, requirement, instance) {
for(var i = 1; i <= requirement; i++)
if (instance.parent.isValid({group: 'block-' + i, force: true}))
return true; // One section is filled, this check is valid
return false; // No section is filled, this validation fails
}
});
Parsley.on('form:submit', function() {
alert("The form would be submitted at this point. " +
"For this demo, we interrupt the processing.");
return false; // Don't submit for this demo
});
$('.demo-form').parsley({
inputs: Parsley.options.inputs + ',[data-parsley-check-children]'
});
});
</script>
您可以在此处查看此代码:parsley example