You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

表单提交时阻止页面刷新失效问题及验证代码求助

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:

  1. You're returning the result of alert(), which always returns undefined (not false). So when you write return alert("Name wrong"), you're effectively returning undefined to the onsubmit event, which doesn't stop the form from submitting.
  2. Your onsubmit handler isn't properly capturing the event or returning the validation result to block the default action.

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 return false/true from your validation function and ensure onsubmit returns that result.

内容的提问来源于stack exchange,提问作者Marinos TBH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:12:28