我不明白为什么我的脚本不起作用。我想在单击提交按钮时验证用户名和密码,但当我键入一个应该返回错误消息的值时,提交只是正常执行。
引用表单元素时出现错误。
您已将引用作为
var form = document.getElementById("form").value;
但应该是
var form = document.getElementById("form");
var name = document.getElementById("name").value;
var pasw = document.getElementById("pasw").value;
var cpasw = document.getElementById("cpasw").value;
var form = document.getElementById("form");
var name_v = /^[a-zA-Z0-9-]+$/;
var pasw_v = /^(?=.*d).{8,}$/;
form.addEventListener("submit", (e) => {
debugger;
let errormsg = [];
if (!name_v.test(name)){
errormsg.push("The Name must not contain spaces or non-word characters");
}
//now for the password
if (!pasw_v.test(pasw)){
errormsg.push("The Name must not contain spaces or non-word characters");
}
if (pasw.length < 8) {
errormsg.push("Password needs to be 8 characters or longer");
}
if (pasw = !cpasw) {
errormsg.push("Passwords must match");
}
if (errormsg.length > 0) {
e.preventDefault();
}
document.getElementById('errorLog').innerText = errormsg.join('n');
});
<div class="formdiv">
<form id="form" method="post" action="manage.html">
<h1>Register</h1>
<label for="email"><b>Email Address</b></label>
<input id="email" type="email" name="email" required></br>
<label for="sName"><b>Screen Name</b></label>
<input id="name" type="text" name="sName" required></br>
<label for="password"><b>Password</b></label>
<input id="pasw" type="password" name="password" required></br>
<label for="cpassword"><b>Confirm Password</b></label>
<input id="cpasw" type="password" name="cpassword" required></br>
<label for="file">Select an avatar: </label>
<input id="avat" type="file" id="file" name="file" required></br>
<button type="submit" id="button2" style="background-color:#4382d4; width: 100%;">Register</button>
</form>
<button type="submit" id="button1" style="background-color:#24a149; margin-top:15px;"
</div>
<div id='errorLog'> </div>
您应该在代码中引用form元素,而不是值
var form = document.getElementById("form");
相反,你是以的身份写作
var form = document.getElementById("form").value; // this is wrong;