Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 58 ยท Forms and Buttons

Form Layout and Validation

Lay out Bootstrap forms with the grid, horizontal and inline patterns, then add needs-validated, was-validated, is-valid and invalid-feedback with a small script.

Single form controls are easy. The real work starts when you put twelve of them on a page and want them to line up on a desktop, stack on a phone, and tell the user clearly what went wrong. Bootstrap does not have a special "form layout" system. It reuses the grid, the spacing utilities and the flex utilities you already know, and adds a small set of classes for validation states.

This lesson shows three layout patterns (grid forms, horizontal forms and inline forms) and then walks through validation: the classes, the browser's built-in checks, and the few lines of JavaScript that tie them together. Make sure you are comfortable with Form Controls and with the grid first.

Grid forms

To lay out a form in columns, put a row around the fields and give each field a column class. The gutter utilities from Gutters, Alignment and Ordering control the spacing, so you rarely need mb-3 on each group inside a row.

A common recipe is row g-3 with col-md-* columns: each field takes the full width on a phone and shares the line from the md breakpoint upward.

A grid form

Resize the preview: below the md breakpoint every field becomes full width. The widths 6 + 6, 6 + 4 + 2 each add up to 12, which is the rule from the grid lesson.

Use col-12 for fields that should always span the whole row, and col-auto for a button or checkbox that should only be as wide as its content.

Horizontal forms

In a horizontal form the label sits to the left of the control. Use row on each field group, put col-form-label on the label (it aligns the text with the input's baseline) and give label and control matching column widths:

HTML
<div class="row mb-3">
  <label for="email" class="col-sm-3 col-form-label">Email</label>
  <div class="col-sm-9">
    <input type="email" class="form-control" id="email">
  </div>
</div>

For a group of radio buttons or checkboxes, the "label" is not tied to one input, so use <fieldset class="row"> with <legend class="col-form-label col-sm-3 pt-0">. That keeps the group semantically correct for screen readers.

A horizontal form

The button uses offset-sm-3 so it lines up under the controls, not under the labels.

Sizing labels in horizontal forms

col-form-label lines a label's text up with a normal-size control. When the control is larger or smaller, the text must match, or the label will float above or below the input's text. Use col-form-label-lg with form-control-lg, and col-form-label-sm with form-control-sm:

Label sizing in a horizontal form

The last row shows form-control-plaintext, which removes the box from a readonly input so a value looks like text but is still part of the form. It is useful for showing an account's email next to editable fields.

Inline forms

An inline form puts everything on one line, like a search bar. There is no special class any more; you build it with the grid and col-auto, or with flex utilities:

HTML
<form class="row row-cols-lg-auto g-3 align-items-center">
  <div class="col-12">
    <label class="visually-hidden" for="q">Search</label>
    <input type="text" class="form-control" id="q" placeholder="Search">
  </div>
  <div class="col-12">
    <button type="button" class="btn btn-primary">Go</button>
  </div>
</form>

row-cols-lg-auto gives each column its natural width from lg upward and stacks them below. A label that you hide visually with visually-hidden still counts for screen readers; never remove a label completely.

How validation works

Browsers already know how to validate: required, type="email", minlength, pattern and min/max are all checked natively. Bootstrap does not replace that. It adds styling for the result and shows messages you write yourself.

flowchart LR
  A["User clicks Submit"] --> B["JS calls checkValidity()"]
  B -->|"false"| C["preventDefault()<br/>add was-validated"]
  B -->|"true"| D["Read the data<br/>and continue"]
  C --> E["CSS shows green or red<br/>and invalid-feedback"]

The browser decides what is valid; one class on the form makes Bootstrap show it.

There are two ways to show states:

  • Server-side or manual: add is-valid or is-invalid to a control yourself. This is what you do after a server tells you "that username is taken".
  • Client-side: add was-validated to the <form>. Bootstrap then styles every control by its :valid and :invalid state with no per-control classes.

Messages live in sibling elements. invalid-feedback is hidden until the control is invalid; valid-feedback until it is valid. They must come right after the control (or inside the same input-group or wrapper), because the CSS uses the sibling selector.

Manual is-valid and is-invalid

Notice the aria-describedby on the first input: it links the control to its message so a screen reader reads the error with the field.

The standard validation script

The script is short. It listens to submit on every form with needs-validation, stops the submit if the form is invalid, and adds was-validated so the styles appear. Put novalidate on the form to turn off the browser's own pop-up bubbles; Bootstrap's messages replace them.

In this lesson's sandbox nothing is sent anywhere. When the form is valid, the handler reads the values with FormData and prints them on the page instead of posting.

Validate, then print the data

Press the button with the form empty and every invalid field turns red with its message. Fill the fields correctly and the printed JSON appears. In a real page you would replace the else branch with a fetch() call, and leave preventDefault() in place so the browser does not reload the page.

Resetting and custom rules

was-validated stays on the form until you remove it. After a successful reset, call form.classList.remove('was-validated') so the next round starts clean. For rules the browser cannot express, such as "the two passwords must match", use input.setCustomValidity('message') when the rule fails and setCustomValidity('') when it passes. The input is then invalid in the eyes of both the browser and Bootstrap.

Client-side validation is a convenience, not security. Anyone can bypass it, so always validate again on the server.

Validation messages as tooltips

By default invalid-feedback and valid-feedback take their own line under the control. In tight layouts, such as table rows or compact toolbars, you can show them as small tooltips instead. Use invalid-tooltip and valid-tooltip in place of the -feedback classes. The tooltip is positioned absolutely, so its parent must be position-relative (adding that class to the wrapper, such as a col, is enough). Everything else, was-validated, is-valid, is-invalid, works as before.

Tooltip-style validation messages

Click Check with empty fields to see the red tooltips, then type a city and a five-digit ZIP to turn them green.

Server-side results and custom validation

When the server decides that a value is wrong, you cannot rely on was-validated, because the browser thinks the value is fine. Render the classes yourself: add is-invalid to the control and put the message the server returned in the following invalid-feedback element. In Laravel, for example, a Blade template adds is-invalid when the field has an error and prints the message in the feedback block; the same idea applies to any server framework.

HTML
<input class="form-control is-invalid" name="email" value="sam@example">
<div class="invalid-feedback">The email must be a valid address.</div>

For custom client rules, combine setCustomValidity() with the same classes. A password-confirmation example: on input, set confirm.setCustomValidity(confirm.value === password.value ? '' : 'Passwords differ'), then read confirm.validationMessage into the feedback element so the user sees what the browser knows. Doing this on every input event gives live feedback; remember that the empty string clears the error.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which markup gives two fields side by side from the md breakpoint and stacked below it?

    col-md-6 applies from md upward; below it the columns default to full width. Bootstrap 5 has no form-inline class.
  2. 2. What does the class col-form-label do in a horizontal form?

    It adds padding and line height so the label lines up with the neighbouring input in the same row.
  3. 3. Why must invalid-feedback come directly after the control?

    Bootstrap shows the message through a sibling rule such as .form-control:invalid ~ .invalid-feedback, so the position matters.
  4. 4. What is the job of the novalidate attribute in the standard pattern?

    Validation (checkValidity) still runs; novalidate only suppresses the built-in pop-ups.
  5. 5. Which class on the form triggers valid and invalid styling for every control at once?

    needs-validation is only a hook for your script; was-validated is the class Bootstrap's CSS reacts to.

Summary

  • Grid forms use row g-3 with col-md-* columns; use col-12 for full-width fields and col-auto for compact ones.
  • Horizontal forms use row, col-form-label and offset-*; use fieldset and legend for radio and checkbox groups.
  • Inline forms are row plus col-auto (or row-cols-lg-auto); keep labels with visually-hidden.
  • Use is-valid and is-invalid for manual states and was-validated for browser-driven states, with valid-feedback and invalid-feedback siblings.
  • A short submit handler calls checkValidity(), prevents the default and adds was-validated; always validate on the server too.

Next lesson: Navs and Tabs.