Lesson 39 +10 XP

Form Validation

Form Validation

Bootstrap provides validation styles to show whether form fields are valid or invalid.

Validation classes

  • .is-valid shows a green border with a checkmark icon.
  • .is-invalid shows a red border with an error icon.
  • .valid-feedback and .invalid-feedback show the message text.

Example with feedback

<div class="mb-3">
  <label for="email" class="form-label">Email</label>
  <input type="email" class="form-control is-invalid" id="email">
  <div class="invalid-feedback">Please enter a valid email.</div>
</div>

<div class="mb-3">
  <label for="name" class="form-label">Name</label>
  <input type="text" class="form-control is-valid" id="name">
  <div class="valid-feedback">Looks good!</div>
</div>

The was-validated trick

Add novalidate to the form and the was-validated class after submission to show validation states without a page reload:

<form class="needs-validation" novalidate>
  <div class="mb-3">
    <input type="text" class="form-control" placeholder="Name" required>
    <div class="invalid-feedback">This field is required.</div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>

JavaScript hook

Bootstrap's example JavaScript checks the needs-validation class, toggles was-validated on submit, and uses the browser's required attribute to decide validity.

Validation tooltips

Use .valid-tooltip and .invalid-tooltip to show messages in a tooltip style instead.

TL;DR

  • .is-valid and .is-invalid mark fields.
  • .valid-feedback and .invalid-feedback show messages.
  • needs-validation + was-validated drive form-wide validation.
  • Feedback shows only when validation has run.