返回 false 在 javascript 验证中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15194782/
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
return false is not working in javascript validation
提问by Ketan
function confirmValidation() {
var confirmPass = document.getElementById('newpassword').value;
var newpass = document.getElementById('newpassword2').value;
var passLength = confirmPass.length;
if ((confirmPass == newpass) && (confirmPass != "" && newpass != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
And input:
并输入:
<input name="register" type="submit" class="alert_button" onclick="return confirmValidation()" value="OK" />
回答by hjpotter92
For the return
method to work, you need to specify onSubmit
attribute/listener to the form
tag itself. Like so:
要使该return
方法起作用,您需要为标签本身指定onSubmit
属性/侦听器form
。像这样:
<form method="post" onsubmit="return confirmValidation();">
<!-- OTHER form fields -->
</form>
From w3cdocumentation:
从w3c文档:
The
onsubmit
event occurs when a form is submitted. It only applies to the FORM element.
该
onsubmit
事件在提交表单时发生。它仅适用于 FORM 元素。
EDIT
编辑
jsfiddle linkadded.
添加了jsfiddle 链接。
You must alter your JavaScript a little so that .focus()
may fire.
您必须稍微更改您的 JavaScript,以便.focus()
可能会触发。
function confirmValidation() {
var confirmPass = document.getElementById('newpassword');
var newpass = document.getElementById('newpassword2');
var passLength = confirmPass.value.length;
if ((confirmPass.value == newpass.value) && (confirmPass.value != "" && newpass.value != "") && (passLength > 8)) {
alert("ok");
return true;
} else {
alert("no");
confirmPass.focus();
return false;
}
}
回答by pdoherty926
Move your validation to the form.
将您的验证移至表单。
document.getElementById('my_form').addEventListener('submit', confirmValidation, false);
回答by Jatin Khurana
You should use onsubmit() event in tag. Now when you submit the form, it will call the function that is written on the onsubmit() event. Only in case of Onsubmit(), it checks the return value if it's true then it proceeds further otherwise not.
您应该在标记中使用 onsubmit() 事件。现在,当您提交表单时,它将调用写在 onsubmit() 事件上的函数。只有在 Onsubmit() 的情况下,它才会检查返回值是否为真,否则它会继续进行,否则不会。
<form method="post" onsubmit="return confirmValidation();">
</form>