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

JavaScript中输入为空或不一致时返回False并弹窗实现方法

Password Validation Implementation for Your Form

Got it, let's get this password validation working properly. Here's a complete, clean solution that checks for empty password fields and mismatched confirm passwords, exactly what you need:

Step 1: Complete Your HTML Form

First, let's finish and adjust your form to include proper IDs for the password fields and hook up the validation function to the form's submit event:

<div class="card margin-card-password">
  <div class="card-header">Change Password</div>
  <div class="card-body">
    <form id="change_password" name="change_password" method="get" action="action/save.php" onsubmit="return validatePassword()">
      <div class="col-sm-6">
        <div class="form-group">
          <label for="new_password">New Password</label>
          <input type="password" class="form-control" id="new_password" name="new_password" placeholder="Enter new password">
        </div>
        <div class="form-group">
          <label for="confirm_password">Confirm Password</label>
          <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm new password">
        </div>
        <button type="submit" class="btn btn-primary">Save Changes</button>
      </div>
    </form>
  </div>
</div>

Step 2: Add the JavaScript Validation Function

Next, add this script (you can put it at the end of your HTML body, or in an external JS file):

function validatePassword() {
  // Grab the trimmed values from the input fields (ignores extra spaces)
  const newPassword = document.getElementById('new_password').value.trim();
  const confirmPassword = document.getElementById('confirm_password').value.trim();

  // Check if the new password field is empty
  if (!newPassword) {
    alert('Please enter a new password');
    return false; // Prevent form submission
  }

  // Check if the two passwords match
  if (newPassword !== confirmPassword) {
    alert('Passwords do not match');
    return false; // Prevent form submission
  }

  // If all checks pass, let the form submit
  return true;
}

Key Details to Note:

  • trim(): This removes any leading/trailing spaces from the input, so users don't get errors from accidental spaces they didn't notice.
  • onsubmit="return validatePassword()": This ensures that if the validation fails (returns false), the form won't send the request to action/save.php.
  • Order of Checks: We first check for an empty password before checking for a mismatch—this gives users clear, step-by-step feedback.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:45:57