表单提交时阻止页面刷新失效问题及验证代码求助
Fix Form Submission Refresh on Validation Failure
Hey there, let's figure out why your form is still refreshing even when validation fails—here's the breakdown and fix:
The Root of the Problem
Your current code has two key issues:
- You're returning the result of
alert(), which always returnsundefined(notfalse). So when you writereturn alert("Name wrong"), you're effectively returningundefinedto theonsubmitevent, which doesn't stop the form from submitting. - Your
onsubmithandler isn't properly capturing the event or returning the validation result to block the default action.
Solution 1: Use e.preventDefault() (Recommended)
This approach first blocks the default form submission behavior, runs your validation, and only submits the form manually if all checks pass.
Updated JavaScript
function validateForm(e) { // Immediately prevent the default form submission behavior e.preventDefault(); // Get input values (add .trim() to ignore whitespace) var name = document.loginForm.name.value.trim(); var email = document.loginForm.email.value.trim(); var password = document.loginForm.password.value; var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // Run validation checks if (name.length === 0) { alert("Name cannot be empty"); return; // Exit the function if validation fails } if (!re.test(email)) { alert('Enter a valid email'); return; } if (password.length < 6) { alert('Password should be at least 6 characters'); return; } // If all checks pass, manually submit the form document.loginForm.submit(); alert('Form submitted'); }
Updated HTML
Make sure to pass the event object to your validation function in the onsubmit attribute:
<div> <form action="" name="loginForm" onsubmit="validateForm(event)"> <label for="name">Name</label> <input name="name" type="text" id="name"> <label for="email">Email</label> <input name="email" type="email" id="email"> <label for="password">Password</label> <input name="password" type="password" id="password"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> </div>
Solution 2: Return false to Block Submission
If you prefer using return values instead of preventDefault(), adjust your code to explicitly return false when validation fails, and ensure the onsubmit handler returns the function's result.
JavaScript
function validateForm() { var name = document.loginForm.name.value.trim(); var email = document.loginForm.email.value.trim(); var password = document.loginForm.password.value; var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (name.length === 0) { alert("Name cannot be empty"); return false; // Return false to block submission } if (!re.test(email)) { alert('Enter a valid email'); return false; } if (password.length < 6) { alert('Password should be at least 6 characters'); return false; } alert('Form submitted'); return true; // Return true to allow submission }
HTML
Update the onsubmit attribute to return the result of validateForm():
<div> <form action="" name="loginForm" onsubmit="return validateForm()"> <label for="name">Name</label> <input name="name" type="text" id="name"> <label for="email">Email</label> <input name="email" type="email" id="email"> <label for="password">Password</label> <input name="password" type="password" id="password"> <button type="submit">Submit</button> <button type="reset">Reset</button> </form> </div>
Key Takeaways
- Never return
alert()directly:alert()doesn't return a boolean value, so it won't block the form submission. Always separate the alert and return statements. - Use
.trim()on input values: This prevents users from submitting just whitespace as a valid name/email. - Choose one blocking method: Either use
e.preventDefault()and manual submission, or returnfalse/truefrom your validation function and ensureonsubmitreturns that result.
内容的提问来源于stack exchange,提问作者Marinos TBH
相关产品推荐
相关产品推荐

