简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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