简体   繁体   English

我的 Javascript 表单验证器不工作(?

[英]My Javascript Form Validator isn't working (?

I can't figure out why my script isn't working.我无法弄清楚为什么我的脚本不起作用。 I'd like to validate the username and the password when clicking the submit button, but when I type a value that should return an error message the submit just executes normally.我想在单击提交按钮时验证用户名和密码,但是当我输入一个应该返回错误消息的值时,提交只会正常执行。

There is a bug when you are referencing the form element.引用表单元素时存在错误。

You have taken the reference as您已将参考作为

var form = document.getElementById("form").value;

But it should be但应该是

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>

You should refer the form element in the code rather than the value您应该在代码中引用表单元素而不是值

 var form = document.getElementById("form");

Instead you are writing as相反,你写成

var form = document.getElementById("form").value; // this is wrong;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM