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

Bootstrap表单验证需求:错误提示、成功状态及字段规则设置

Bootstrap Form Validation with Custom Rules & Real-Time Feedback

Got it, let's build this validation step by step. Bootstrap has great built-in validation utilities, and we can extend them to meet your exact requirements. Here's a complete implementation that covers all your needs:

Step 1: HTML Form Structure

First, set up your form with Bootstrap's form classes, including dedicated feedback elements for success and error states. We'll use Bootstrap's native validation classes to keep the design consistent.

<form id="myForm" class="needs-validation" novalidate>
  <!-- Email Field -->
  <div class="mb-3">
    <label for="email" class="form-label">Email address</label>
    <input type="email" class="form-control" id="email" required>
    <div class="invalid-feedback">
      Please enter a valid email address (must include @).
    </div>
    <div class="valid-feedback">
      Looks good!
    </div>
  </div>

  <!-- Phone Number Field -->
  <div class="mb-3">
    <label for="phone" class="form-label">Phone Number</label>
    <input type="text" class="form-control" id="phone" required>
    <div class="invalid-feedback">
      Please enter a valid 10-digit phone number.
    </div>
    <div class="valid-feedback">
      Looks good!
    </div>
  </div>

  <!-- Submit Button -->
  <button class="btn btn-primary" type="submit">Submit Form</button>
</form>

Step 2: Custom Validation Logic

Add JavaScript to enforce your specific rules, provide real-time feedback as the user types, and block form submission until all fields are valid.

// Grab form and field elements
const form = document.getElementById('myForm');
const emailField = document.getElementById('email');
const phoneField = document.getElementById('phone');

// Custom validation helpers
function isValidEmail(email) {
  // Basic check for @ symbol (extend with stricter regex if needed)
  return email.includes('@');
}

function isValidPhone(phone) {
  // Regex to match exactly 10 digits
  const phoneRegex = /^\d{10}$/;
  return phoneRegex.test(phone);
}

// Real-time validation on user input
emailField.addEventListener('input', function() {
  if (isValidEmail(this.value)) {
    this.classList.remove('is-invalid');
    this.classList.add('is-valid');
  } else {
    this.classList.remove('is-valid');
    this.classList.add('is-invalid');
  }
});

phoneField.addEventListener('input', function() {
  if (isValidPhone(this.value)) {
    this.classList.remove('is-invalid');
    this.classList.add('is-valid');
  } else {
    this.classList.remove('is-valid');
    this.classList.add('is-invalid');
  }
});

// Handle form submission
form.addEventListener('submit', function(event) {
  // Block submission if any field fails validation
  const allFieldsValid = form.checkValidity() && isValidEmail(emailField.value) && isValidPhone(phoneField.value);
  
  if (!allFieldsValid) {
    event.preventDefault();
    event.stopPropagation();
  }

  // Trigger Bootstrap's validation styles
  form.classList.add('was-validated');
});

Key Features Breakdown

  • Real-Time Feedback: Fields update instantly to show green (valid) or red (invalid) states as the user types, with clear error/success messages.
  • Custom Rules:
    • Email must contain an @ symbol (swap in a stricter regex like ^[^\s@]+@[^\s@]+\.[^\s@]+$ if you need to validate full domain structure).
    • Phone number must be exactly 10 digits (no letters or special characters allowed).
  • Submit Blocking: The form will only submit if all fields are filled, pass custom validation, and meet Bootstrap's required check.
  • Bootstrap Consistency: Uses native Bootstrap classes (is-valid, is-invalid, valid-feedback) so styles match your existing Bootstrap setup.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:24:50