【发布时间】:2021-02-16 08:32:44
【问题描述】:
我正在做表单验证,当我在表单中使用“onsbmit”调用我的函数“validtae()”时,它不起作用。当我单击按钮提交假设发生的验证不起作用我不知道为什么它不起作用,我尝试在 onsubmit 中添加返回仍然不起作用。我尝试在输入标签内使用 onfocus 调用该函数,它可以工作,但是当我单击按钮时我想工作。
// getting inputs
const namee = document.forms['myForm']['name'];
const email = document.forms['myForm']['email'];
const password =document.forms['myForm']['password'];
// getting where the erroe gonna show
const nameerror = document.querySelector('#nameerror');
const emailerror = document.querySelector('#emailerror');
const passworderror = document.querySelector('#passworderror');
// validation function
function validate(){
if(namee.value == "" ){
namee.style.border = "2px solid red";
nameerror.textContent ="name cannot be blank";
namee.focus();
return false;
}
if(email.value == "" ){
email.style.border = "2px solid red";
emailerror.textContent ="email cannot be blank";
email.focus();
return false;
}
if(password.value == "" ){
password.style.border = "2px solid red";
passworderror.textContent ="password cannot be blank";
password.focus();
return false;
}
}
<form name="myForm" method="post" onsubmit="return validate()">
<input type="text" id="name" name="name" placeholder="Name" required>
<div id="nameerror"></div>
<input type="email" id="email" name="email" placeholder="Email" required>
<div id="emailerror"></div>
<input type="password" id="password" name="password" placeholder="Create a password"
required>
<button id="submit" type="submit">Sign Up</button>
</form>
【问题讨论】:
-
我的直觉是浏览器自己对
required属性的验证在调用onsubmit之前就开始了。如果这不是您想要的,请删除required属性。 -
恕我直言,您应该完全重新考虑您的验证 JS。此外,在 HTML 代码中没有 passworderror
div. -
只需将
noValidate添加到您的表单中,如下所示:<form name="myForm" method="post" onsubmit="return validate()" noValidate>
标签: javascript