25.9. Validation with JavaScript

Validating form inputs before submitting the form can make the user experience much smoother. Some input types have built-in browser validation for basic formats such as numbers and email addresses. We can use event handlers to perform more complex validation on form input values.

25.9.1. Form Inputs and the DOM

Before we can validate what the user has typed we need to understand how to use form inputs with the DOM. Remember that the DOM is a JavaScript representation of the HTML document. <input> tags can be selected and referenced like any other HTML element.

To read the value of an input, we can check the value attribute. We can also assign a new value to input.value which will update the value shown in the input.

Example

This example will log the value of an input, update the input's value, and then log it again when the button is clicked.

 1<!DOCTYPE html>
 2<html>
 3<head>
 4      <title>Check input value with DOM</title>
 5</head>
 6<body>
 7   <form>
 8      <label>Language
 9         <input type="text" name="language" id="language" value="JavaScript">
10      </label>
11   </form>
12   <button id="update">Update Input Value</button>
13   <script>
14      let button = document.getElementById("update");
15      // add event handler for when button clicked
16      button.addEventListener("click", function() {
17         let input = document.getElementById("language");
18         console.log(input.value);
19         // now update the value in the input
20         input.value = input.value + " rocks!";
21         console.log(input.value);
22      });
23   </script>
24</body>
25</html>

Question

What happens when you click the button multiple times?

25.9.2. Steps to Add Validation

  1. Add an event handler for the window load event
  2. Within the window's load handler, add an event handler for the form submit event
  3. Retrieve input values that need to be validated from the DOM.
  4. Within the form's submit handler, check the input values using conditional statements
    1. If the values are valid, allow the form submission
    2. If the values are NOT valid, inform the user and STOP form submission

Each of these steps involves additional details, which we will now break down.

Example

Let's start this by showing an alert box when the form submit event is triggered.

 1<html>
 2   <head>
 3      <title>Form Validation</title>
 4      <style>
 5         label {display: block;}
 6         body {padding: 25px;}
 7      </style>
 8   </head>
 9   <script>
10      window.addEventListener("load", function() {
11         let form = document.querySelector("form");
12         form.addEventListener("submit", function(event) {
13            alert("submit clicked");
14         });
15      });
16   </script>
17   <body>
18      <form method="POST" action="https://handlers.education.launchcode.org/request-parrot">
19         <label>Username <input type="text" name="username"></label>
20         <label>Team Name <input type="text" name="team"></label>
21         <button>Submit</button>
22      </form>
23   </body>
24</html>

25.9.3. Follow Along as We Add Validation

Use this repl.it and the following instructions to add validation to the above example.

Get Reference to Inputs

To validate what the user has typed, we can get a reference to the input elements in the DOM and check the value property of each. Let's change the submit event handler to display the value of the username input in an alert box. To do that, we are going to use document.querySelector("input[name=username]"), which uses an attribute selector to select the <input> that has name="username".

 1<script>
 2   window.addEventListener("load", function() {
 3      let form = document.querySelector("form");
 4      form.addEventListener("submit", function(event) {
 5         let usernameInput = document.querySelector("input[name=username]");
 6         // alert the current value found in the username input
 7         alert("username: " + usernameInput.value);
 8      });
 9   });
10</script>

Alert the Input Values When Submitted

Now that we know how to get the value of an input, we can add conditional statements. Let's add code that opens an alert box if either input value is empty.

 1<script>
 2   window.addEventListener("load", function() {
 3      let form = document.querySelector("form");
 4      form.addEventListener("submit", function(event) {
 5         let usernameInput = document.querySelector("input[name=username]");
 6         let teamName = document.querySelector("input[name=team]");
 7         if (usernameInput.value === "" || teamName.value === "") {
 8            alert("All fields are required!");
 9         }
10      });
11   });
12</script>

We are making progress. Now if you click Submit with one or both of the inputs empty, then an alert message appears telling you that both inputs are required. However, the form is still submitted even if the data is invalid.

Prevent Form Submission

We should prevent the form submission from happening until all inputs have valid values. We can use the event parameter and event.preventDefault() to stop the form submission. event.preventDefault() prevents default browser functionality from happening, like form submission when <button> tags are clicked inside of a form. Remember that event handler functions are passed an event argument which represents the event that the handler is responding to.

 1<script>
 2   window.addEventListener("load", function() {
 3      let form = document.querySelector("form");
 4      form.addEventListener("submit", function(event) {
 5         let usernameInput = document.querySelector("input[name=username]");
 6         let teamName = document.querySelector("input[name=team]");
 7         if (usernameInput.value === "" || teamName.value === "") {
 8            alert("All fields are required!");
 9            // stop the form submission
10            event.preventDefault();
11         }
12      });
13   });
14</script>

25.9.4. Check Your Understanding

Question

What method on the event object can be used to stop a form submission?