簡體   English   中英

我的 Javascript 表單驗證器不工作(?

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

我無法弄清楚為什么我的腳本不起作用。 我想在單擊提交按鈕時驗證用戶名和密碼,但是當我輸入一個應該返回錯誤消息的值時,提交只會正常執行。

引用表單元素時存在錯誤。

您已將參考作為

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>

您應該在代碼中引用表單元素而不是值

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

相反,你寫成

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM