当我按下“提交”按钮时,我需要在表单提交之前验证表单。我知道我应该使用preventDefault
,但我不确定如何正确使用它:
function validateName() {
var name = form.firstname.value;
if (name == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else {
document.getElementById("firstnameInvalid").style.visibility = "hidden";
}
}
<form name="form" method="post" onsubmit="return validate(this)">
<p>First Name:
<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" />
<span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
</p>
答案 0 :(得分:0)
您可以通过在验证码中添加return
语句来停止表单。当函数返回onsubmit
时,false
将停止提交表单。
答案 1 :(得分:0)
正如其他人所说,在onsubmit
回调中返回false会阻止提交表单。
var form = document.getElementById( 'idgoeshere' );
form.onsubmit( function() {
// validate here
return false;
});
答案 2 :(得分:0)
您的validate()
必须返回真值或假值才能使用onsubmit="return validate(this)"
尝试类似
的内容function validate(variable)
{
if(condition) //add a condition to validate
{
return false; //if condition are met, return false and do not submit
}
//you can create more than one condition following this logic.
return true; //if none of the conditions are met, he return true and submit
}