如果密码不匹配,我已经设法弄清楚如何“错误”警报,但这并不能阻止用户仍然完全提交表单。有人可以解释一下我如何编写一个语句,在允许用户使用 onsubmit 函数提交表单之前检查所有内容是否返回 true 吗?
请注意,我知道我没有编写一个名为 validateForm 的函数,该函数在表单的 onsubmit HTML 中注明,我只知道当我编写此函数时需要它
这是 jsfiddle 的链接:http: //jsfiddle.net/shanny/VSUM6/28/
这是代码:
HTML:
<html>
<h1>Form Validation</h1>
<div id="error"></div>
<form name="myForm" action="" method="post" target="_blank" onsubmit="return validateForm()">
First Name: <input type="text" name="firstName" autofocus required >
<br />
Last Name: <input type="text" name="lastName" required >
<br />
Email: <input id="email" type="email" name="email" placeholder="e.g., name@provider.com" required>
<br />
Password: <input type="password" name="password1" id="password1" required >
<br />
Confirm Password: <input type="password" name="password2" id="password2" required > <p id="error2"></p>
<br /><br />
Sex:
<input type="radio" name="sex" value="male" >Male
<input type="radio" name="sex" value="female">Female
<br /><br />
Quantity:<br />
<input name ="scale" type="range" min="1" max="6" step="1" value="1" >
<br />
1 2 3 4 5 6
<br /><br />
Interests (select all that apply):
<br />
<input type="checkbox" class="radio" name="interests" value="running">This
<input type="checkbox" class="radio" name="interests" value="swimming">That
<input type="checkbox" class="radio" name="interests" value="hiking">Other
<br /><br />
<input name="submit" id="submit" type="submit" value="Hayo!">
</form>
</html>
JavaScript:
var errorBox=document.getElementById("error");
var errorText=document.getElementById("error2");
var pass2=document.getElementById("password2");
var pass1=document.getElementById("password1");
pass2.onchange = function() {
if (pass2.value !== pass1.value) {
pass2.style.border="2px solid red";
errorText.innerHTML="Passwords do not match!";
errorText.style.color="red";
//errorBox.style.height="40px";
//errorBox.style.visibility="visible";
//errorBox.innerHTML="<p>Passwords do not match!</p>";
return false;
}
else {
pass2.style.border="2px solid #B5DCF7";
errorText.style.color="green";
errorText.innerHTML="Passwords match!";
return true;
}
};