left-icon

Twitter Bootstrap 4 Succinctly®
by Peter Shaw

Previous
Chapter

of
A
A
A

CHAPTER 9

A Form of Data Entry

A Form of Data Entry


The one thing that hasn’t changed very much in BS4 is the form components. The general premise of using the standard HTML5 <form> and <input> tags and styling them at an element level rather than adding extra classes is still very much the most basic way of using BS4 on your forms.

In reality, to get the best out of BS4’s forms, you’ll want to at least use the form-group, form-control, and form-text classes. By doing this for really simple forms, you can make sure that your inputs and their associated labels are associated with each other correctly, and more importantly, are easy to style with the validation helpers and make sense to assistive technologies using their various ARIA role attributes.

The most basic form that you can produce using these base classes in BS4 looks something like this:

A very basic form

Figure 70: A very basic form

In this format, the labels are above the inputs, the inputs are wrapped in a <div> using the form-group class, along with their respective labels, and a <span> or other inline element using form-help is placed under the <input> element to provide the help text.

The code to produce the form is quite simple.

Code Listing 70: The markup for the basic form shown in Figure 70

  <!-- Page content goes here -->

  <div class="container">

    <div class="row">

      <div class="col">

        <br />

        <form>

          <div class="form-group">

            <label for="email">Email address</label>

            <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">

            <small id="emailHelp" class="form-text text-muted">Please enter your email in this box. We won't spam you in any way, shape, or form.</small>

          </div>

          <div class="form-group">

            <label for="password">Password</label>

            <input type="password" class="form-control" id="password" aria-describedby="passwordHelp" placeholder="Password">

            <small id="passwordHelp" class="form-text text-muted">Enter your password here. It's OK, you can trust us. We’re not going to steal it.</small>

          </div>

          <div class="form-check">

            <input type="checkbox" class="form-check-input" id="confirm">

            <label class="form-check-label" for="confirm">Select me to allow us to abuse your data wholesale as we see fit.</label>

          </div>

          <button type="submit" class="btn btn-primary">Submit</button>

        </form>

      </div>

    </div>

  </div>

There are a few things you need to take note of in Code Listing 70. First, notice that the label for the attribute is the same value as the actual ID assigned to the input control. This is not a BS4 thing, but an HTML5 thing that allows assistive tech to know which label belongs to which control.

If you don’t want to use labels on your forms, then you should still create label tags in your HTML but hide them from display by using the sr-only class. Adding this as the final class on the other classes in the attribute will effectively hide your label from the browser rendering process, but will still allow assistive technologies to tell the user what the input field represents.

The second thing to note is the aria-describedby attribute on the input control. Again, like the label, the value of this is the ID of another element in the group. This time, however, it’s the ID of the inline element with the class form-text, which, if present, will be used by screen readers to provide extra context-sensitive descriptions to the user.

The final point to note is the order of the check box and the label for the check box control. In order for the label to render correctly, the label must always follow the input. This is a limitation of HTML, not anything in BS4.

The biggest change in forms for BS4 is in the layout possibilities they provide thanks to the Flexbox-first policy that BS4 now uses.

If we strip Code Listing 70 back to just input elements in a row with col <div>s, we can easily achieve the following output.

Inputs arranged horizontally using columns

Figure 71: Inputs arranged horizontally using columns

We can use all the grid-based classes such as col, col-md-*, and row inside and outside of form-groups, and with plain old input elements on their own.

The one place where this really changes, however, is in producing horizontal forms.

In previous versions of Bootstrap, there existed specific classes for aligning forms horizontally. Now, all you need to do is add an additional row class to your <div> that forms the form-group, and then divide the inner space using col-based classes on the labels and input elements as needed. For example:

Code Listing 71: A small change makes horizontal forms easy

  <!-- Page content goes here -->

  <div class="container">

    <div class="row">

      <div class="col">

        <br />

        <form>

          <div class="form-group row">

            <label for="email" class="col-sm-2 col-form-label">Email</label>

            <div class="col-sm-10">

              <input type="email" class="form-control" id="email" placeholder="Email">

            </div>

          </div>

          <div class="form-group row">

            <label for="password" class="col-sm-2 col-form-label">Password</label>

            <div class="col-sm-10">

              <input type="password" class="form-control" id="password" placeholder="Password">

            </div>

          </div>

          <div class="form-group row">

            <div class="col-sm-10">

              <button type="submit" class="btn btn-primary">Sign in</button>

            </div>

          </div>

        </form>

      </div>

    </div>

  </div>

This is in stark contrast to BS3, which involved an HTML structure that was a bit different from the general one shown in Code Listing 71, and a number of class name changes. In BS4, it’s much easier to have forms switch between the horizontal layout and vertical layout, depending on the screen or device size and orientation.

Code Listing 71 should produce the following output when rendered using your BS4 template.

Horizontal forms are now much easier

Figure 72: Horizontal forms are now much easier

If you use col-auto instead of col when breaking up your forms on the grid, you can get your controls to only use as much space as is needed to draw the control and its contents. This comes in handy if you use the form-inline class directly on the <form> tag of your form, which will force your entire form to run along one line. (This is exactly what the navbar form does internally when you add a form to a navigation bar.)

Aside from the layout possibilities, adding disabled, readonly, and the various new types as defined in the HTML5 specification will cause BS4 to react appropriately and style the form elements as needed to show them in read-only, disabled, or both states when rendered.

Form validation

The final change that might come as a bit of a shock is the validation helpers.

In BS3, you added various classes such as has-error, has-warning, and others to the actual <form> elements or <div> elements containing the form groups.

While these still exist in BS4, the recommended way is now to use the HTML5 Validation API. With the use of four new classes, everything is handled for you by BS4—you no longer have to start adding and removing lots of classes in lots of places as you did with BS3.

Take a look at the following HTML code.

Code Listing 72: BS4 form using HTML5 validation

  <!-- Page content goes here -->

  <div class="container">

    <div class="row">

      <div class="col">

        <br />

        <form class="needs-validation" novalidate>

          <div class="form-row">

            <div class="col-md-4 mb-3">

              <label for="firstName">First name</label>

              <input type="text" class="form-control" id="firstName" placeholder="First name" required>

              <div class="valid-feedback">That's great thanks</div>

              <div class="invalid-feedback">Please enter your first name here</div>

            </div>

            <div class="col-md-4 mb-3">

              <label for="lastName">Last name</label>

              <input type="text" class="form-control" id="lastName" placeholder="Last name" required>

              <div class="valid-feedback">That's great thanks</div>

              <div class="invalid-feedback">Please enter your last name here</div>

            </div>

          </div>

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

        </form>

      </div>

    </div>

  </div>

Notice that it’s mostly just a standard BS4 form layout using form rows, groups, and input types with labels.

Take a look at the opening <form> tag. Notice the needs-validation class that’s been added to it, along with the novalidate attribute.

The novalidate attribute is added to stop the browser from attempting to apply the regular HTML5 validation to the form when it first loads. The needs-validation class tells BS4 not to style any of the input elements or groups, or to activate any validation states. What this means is that the form looks like the following figure when it’s first loaded.

The BS4 form from Code Listing 72 when it’s first loaded

Figure 73: The BS4 form from Code Listing 72 when it’s first loaded

There is nothing particularly surprising here, but if you now change the class on the <form> tag from needs-validation to was-validated, and then press F5 to reload your form, it should now look like this:

The BS4 form from Code Listing 72 with the single class changed on the parent form

Figure 74: The BS4 form from Code Listing 72 with the single class changed on the parent form

That one change tells BS4 that you’ve now validated the form, and that it now has to show the different styles to indicate that there are failures in the validation. Notice that the different colors work automatically. If you type something into one of the boxes, for example, you’ll see the validation state change along with the text below the input field.

What’s more, you haven’t had to change any classes manually to make this happen, as you used to have to do under BS3. Instead, Bootstrap has interrogated the input controls using the HTML5 Validation API, and if you look at the two input text boxes used, you’ll see they have required attributes.

What’s happening here is you’re setting the novalidate attribute on the form so that the HTML5 Validation API allows you to click the Submit button. In your Submit button handler, you would then check the state manually in JavaScript, and if your validation was not satisfied, you’d change the CSS class on the form to was-validated and let BS4 do the rest of the heavy lifting for you.

If you look at the <div> elements underneath the inputs, you’ll see that they each have two <div> elements: one with a valid-feedback class and one with an invalid-feedback class on it. If the form passes validation, valid feedback elements are unhidden, and invalid feedback elements remain hidden. If validation fails, the opposite is performed, and invalid feedback elements are shown.

A suitable JavaScript function to handle this might look like the following code listing (taken straight from the BS4 docs).

Code Listing 73: A small JavaScript function for handling BS4 form validation

       <script>

          (function() {

            'use strict';

            window.addEventListener('load', function() {

            var forms = document.getElementsByClassName('needs-validation');

            var validation = Array.prototype.filter.call(forms, function(form) {

            form.addEventListener('submit', function(event) {

              if (form.checkValidity() === false) {

                event.preventDefault();

                event.stopPropagation();

              }

              form.classList.add('was-validated');

            }, false);

          });

          }, false);

        })();

      </script>

At page load, we use the jQuery ready handler to run a small routine that looks for and attaches a handler to every form in the page that has the needs-validation class. This handler intercepts the form’s submit call so that when the form is submitted, it stops the submission from taking place. Only if checkValidity in the HTML5 Validation API tells it that the form has no invalid elements does the routine then reverse that block and allow the form to be submitted.

This has the benefit that, if JavaScript is disabled, the standard form submission process still works as expected, but no validation takes place.

Of course, you can add any validation mechanism you like here, and use any validation method you want. All that matters is that the form’s validation state is reported as valid or invalid, and the class on the <form> tag is changed as required.

Again, there’s more to be seen, so as with previous chapters, I encourage you to go to the forms documentation in the BS4 docs and continue from there.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.