Chapter 7. Forms

Introduction

Forms collect user input that is submitted to a remote URL or API endpoint. Modern browsers have many built-in form input types for text, numbers, colors, and more. A form is one of the main ways you get input from your user.

FormData

The FormData API provides a data model for accessing form data. It saves you the trouble of having to look up individual DOM elements and get their values.

Even better, once you have a FormData object, you can pass it directly to the Fetch API to submit the form. Before submission, you can alter or add to the data in the FormData object.

Validation

To prevent users from sending invalid data, you can (and should) add client-side validation for your forms. This could be something as simple as marking a field as required, or more complex validation logic that involves coordinating multiple form values or calling an API.

In the past, a developer would usually need to reach for a JavaScript library to perform form validation. This could cause headaches due to data duplication; it exists in the form data and an in-memory object used by the validation library.

HTML5 added more built-in validation options, such as:

  • Marking a field as required

  • Specifying the minimum and maximum values in a number field

  • Specifying a regular expression to validate the field’s input

These options are used as attributes on the <input> elements.

The browser shows basic validation error messages (see Figure 7-1), but the style may not look ...

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.