R
Rishtaara
Bootstrap 5 Fundamentals
Lesson 17 of 24Article18 min

Input Groups, Floating Labels & Validation

Input groups attach text, buttons, or icons before or after a field. Wrap in .input-group with .input-group-text for addons.

Input Groups

Input groups attach text, buttons, or icons before or after a field. Wrap in .input-group with .input-group-text for addons.

Real-life example: An input group is like a price tag with the rupee symbol fixed on the left — the number goes in the box, the symbol stays put.

Input group with prefix and button
<div class="input-group mb-3">
  <span class="input-group-text">@</span>
  <input type="text" class="form-control" placeholder="Username" />
</div>

<div class="input-group">
  <input type="search" class="form-control" placeholder="Search courses" />
  <button class="btn btn-outline-secondary" type="button">Go</button>
</div>

Floating Labels

Floating labels animate the label inside the field border. Use .form-floating wrapping an input and a <label> placed after the input.

Real-life example: Floating labels are like name tags that slide up to the edge when you start writing — saving space until you need the hint.

Floating label field
<div class="form-floating mb-3">
  <input type="email" class="form-control" id="floatEmail" placeholder="name@example.com" />
  <label for="floatEmail">Email address</label>
</div>

Validation

Bootstrap validation uses .was-validated on the form or .is-valid / .is-invalid on fields. Pair with .valid-feedback and .invalid-feedback messages.

HTML5 required, pattern, and type="email" work with browser validation; Bootstrap adds green/red styling.

Real-life example: Validation is like a teacher marking answers — green tick when correct, red note when something is missing.

Validated form
<form class="row g-3 needs-validation" novalidate>
  <div class="col-md-6">
    <label for="city" class="form-label">City</label>
    <input type="text" class="form-control" id="city" required />
    <div class="invalid-feedback">Please enter your city.</div>
  </div>
  <div class="col-12">
    <button class="btn btn-primary" type="submit">Submit</button>
  </div>
</form>

<script>
  (() => {
    const forms = document.querySelectorAll(".needs-validation");
    forms.forEach((form) => {
      form.addEventListener("submit", (e) => {
        if (!form.checkValidity()) {
          e.preventDefault();
          e.stopPropagation();
        }
        form.classList.add("was-validated");
      });
    });
  })();
</script>