如何在提交时验证此 HTML/JavaScript 表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18851684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I validate this HTML/JavaScript form onsubmit?
提问by Shannon
I have managed to figure out how to 'error' alert if the passwords do not match, but this does not prevent a user from still submitting the form altogether. Can someone please explain how I can write a statement that checks that everything returns true before allowing the user to submit the form with an onsubmit function?
我已经设法弄清楚如何在密码不匹配时发出“错误”警报,但这并不能阻止用户仍然完全提交表单。有人可以解释一下我如何编写一个语句,在允许用户使用 onsubmit 函数提交表单之前检查所有内容是否返回 true?
Please note that I understand that I have not written a function called validateForm that is noted in the onsubmit HTML of the form, I just know that this needs to be there for when I have written this function
请注意,我知道我没有编写一个名为 validateForm 的函数,该函数在表单的 onsubmit HTML 中注明,我只知道在我编写此函数时需要存在该函数
Here is the link to the jsfiddle: http://jsfiddle.net/shanny/VSUM6/28/
这是 jsfiddle 的链接:http: //jsfiddle.net/shanny/VSUM6/28/
And here is the code again:
这是代码:
HTML:
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., [email protected]" 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:
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;
}
};
采纳答案by nderscore
The easiest way to prevent the default behavior of the form submit is to have your function return false. This will stop the form from submitting.
防止表单提交的默认行为的最简单方法是让您的函数返回 false。这将阻止表单提交。
var onSumbitHandler = function(event){
/* validate here */
return false;
};
The other (and technically better) way is to call preventDefault on the event object that is passed as a parameter to your onSubmit function. The only issue is that some older versions of IE don't support this method, so you'll need to provide a fallback for this case:
另一种(技术上更好)的方法是在作为参数传递给 onSubmit 函数的事件对象上调用 preventDefault 。唯一的问题是一些旧版本的 IE 不支持这种方法,因此您需要为这种情况提供后备:
var onSubmitHandler = function(event){
/* validate here */
if(event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
};
回答by Leif Arne Storset
Use the cool, new-ish Constraint Validation API:
使用酷炫的新约束验证 API:
const setPasswordValidity = () => {
const valid = pass2.value === pass1.value;
for (let el of [pass1, pass2]) {
if (valid) el.setCustomValidity("");
else el.setCustomValidity("Passwords do not match!");
}
};
pass1.onchange = setPasswordValidity;
pass2.onchange = setPasswordValidity;
setPasswordValidity();
回答by mikekavouras
Historically, I have used the following idea:
从历史上看,我使用了以下想法:
function validateForm() {
var errors = 0;
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var firstName = document.getElementById("firstName").value;
var lastName = document.getelementById("lastName").value;
// etc..
// validate required fields
if (firstName === "") {
errors++;
}
if (lastName === "") {
errors++;
}
// etc...
return errors === 0;
}
You can also make the errors more robust...
您还可以使错误更加健壮......
function validateForm() {
var errors = [];
var form = document.getElementsByTagName('form')[0];
/*
* Store appropriate form elements.
* There are many ways to do this, but I'm keeping it
* simple for the example
*/
var fnElem = document.getElementById("firstName");
var lnElem = document.getelementById("lastName");
var firstName = fnElem.value;
var lastName = lnElem.value;
// etc...
// validate required fields
if (firstName === "") {
errors.push({
elem: firstName,
message: "First name can't be blank"
});
}
if (lastName === "") {
errors.push({
elem: lastName,
message: "Last name can't be blanks"
});
}
// etc...
return errors.length === 0;
}
You could then loop through the errors and do something useful.
然后,您可以遍历错误并做一些有用的事情。