Skip to content

Form validation

The first rule of web development is simple: never trust any user input.

This is because users can enter anything they want into a form field, and it’s up to you to make sure that the data is valid and safe to use.

This tutorial will walk you through how to validate user input in a sign-up form for Harmony Music Academy.

The simplest form of validation is to check if a field is empty or not. This is known as presence checking.

In our sign-up form, we want to make sure that the user has entered their email address, level, and hours per week.

Let’s start by seeing what happens when we submit the form without entering any data.

  1. If you have been following the steps in the previous tutorial on Capturing Form Data, you should already have the following code inside your index.js file:

    index.js
    // Capture user's input on form submission
    let form = document.querySelector("form");
    form.addEventListener("submit", function (event) {
    event.preventDefault();
    // Store the user's email address as userEmail (string/text)
    let userEmail = document.querySelector("#email").value;
    // Store the user's level as userLevel (string/text)
    let userLevel = document.querySelector("#level").value;
    // Store the user's hours of study as userHours (number)
    let userHours = document.querySelector("#hoursPerWeek").value;
    console.log({ userEmail, userLevel, userHours });
    });
    7 collapsed lines
    // Validate the user's input
    // Check if the user has selected a level
    // Check if the user has provided an email address
    // Check if the user has specified at least one hour of study
    // Check if the number of hours requested is within the allowed range
    // Calculate the total cost
    // Display the total cost to the user
  2. With this code in place, start your application server in the usual way.

  3. In your browser, open up the dev tools, and navigate to the β€˜Console’ tab.

  4. Submit the form without entering any data. You should see the following output in the console:

    logging-empty-form-values

    As you can see, the userEmail and userHours values are empty strings, while userLevel is string that reads 'basic'.

    { userEmail: "", userLevel: "basic", userHours: "" }

Let’s spend a moment to understand where these values are coming from.

Now that we know where our form values are coming from, let’s think how we can add a validation check that ensures that the user has entered an email address.

  1. Inside index.js, just above the console.log() statement, add a conditional check like so:

    index.js
    // Capture user's input on form submission
    let form = document.querySelector("form");
    form.addEventListener("submit", function (event) {
    event.preventDefault();
    // Store the user's email address as userEmail (string/text)
    let userEmail = document.querySelector("#email").value;
    // Store the user's level as userLevel (string/text)
    let userLevel = document.querySelector("#level").value;
    // Store the user's hours of study as userHours (number)
    let userHours = document.querySelector("#hoursPerWeek").value;
    // Validate the user's input
    // Check if the user has provided an email address
    if (userEmail === "") {
    alert("Please enter your email address.");
    return;
    }
    console.log({ userEmail, userLevel, userHours });
    });
  2. Save your changes, and head back over to your browser.

    Make sure your devtools console is still open, and try submitting an empty form again.

    This time, you should see an alert message that says β€œPlease enter your email address.”

    alert-empty-email

  3. Did you notice something else as well? The console.log() statement is no longer executed when the email field is empty.

    Can you work out why?

    This is because the return statement inside the if block stops the function from executing any further.

    if (userEmail === "") {
    alert("Please enter your email address.");
    return;
    }

    Any time you see a return statement inside a function, it means that the function will stop executing the code inside it at that point and return whatever value we have told it to.

    (In this case, the function returns undefined, because we haven’t specified a value to return.)

    Because of this, the console.log() statement is never reached when the email field is empty.

    This behaviour is useful because it allows us to stop the computer processing data unnecessarily if any of the fields are empty.

    Click to reveal
  4. Now that we have a check in place for the email field, let’s add similar ones to validate the other form fields.

Presence checking is one thing, but we also need to make sure that the data entered by the user is valid.

Let’s start by checking if the user has entered a valid email address.

This is actually surprising easy!

  1. Open index.html

  2. Locate the input field for the user’s email address.

    It should be around line 17, and look like this:

    index.html
    <input
    id="email"
    name="email"
    type="text"
    class="form-input"
    placeholder="Your email"
    />
  3. The type attribute of the input field is set to text, which means that it accepts any kind of text input.

    All we need to do is change this to email:

    index.html
    <input
    id="email"
    name="email"
    type="email"
    class="form-input"
    placeholder="Your email"
    />
  4. With this in place, if you submit a value in the email field that is not a valid email address, the browser will automatically display an error message.

    Email content validation

One surprisingly tricky check is to ensure that users must enter a positive integer for the number of hours.

  1. Open index.js

  2. Before we can check if the number is positive or not, we need to convert the value of userHours to a number.

    This is because the value of an input field is always a string, even if the HTML input field is of type number.

    To convert the value to a number, we can use the built-in JavaScript parseInt() function.

    Remove the line highlighted in red below, and replace it with the code highlighted in green:

    index.js
    form.addEventListener("submit", function (event) {
    event.preventDefault();
    let userEmail = document.querySelector("#email").value;
    let userLevel = document.querySelector("#level").value;
    let userHours = document.querySelector("#hoursPerWeek").value;
    let userHours = document.querySelector("#hoursPerWeek").value;
    let userHours = parseInt(document.querySelector("#hoursPerWeek").value);
    12 collapsed lines
    if (userEmail === "") {
    alert("Please enter your email address.");
    return;
    }
    if (userHours === "") {
    alert("Please enter at least one hour of tuition.");
    return;
    }
    console.log({ userEmail, userLevel, userHours });
    });
  3. Now we can check whether the actual value is a positive number. But this is where it gets tricky.

    Remove the previous check, and modify it as follows:

    index.js
    // Capture user's input on form submission
    let form = document.querySelector("form");
    form.addEventListener("submit", function (event) {
    event.preventDefault();
    20 collapsed lines
    // Store the user's email address as userEmail (string/text)
    let userEmail = document.querySelector("#email").value;
    // Store the user's level as userLevel (string/text)
    let userLevel = document.querySelector("#level").value;
    // Store the user's hours of study as userHours (number)
    let userHours = parseInt(document.querySelector("#hoursPerWeek").value);
    // Validate the user's input
    // Check if the user has provided an email address
    if (userEmail === "") {
    alert("Please enter your email address.");
    return;
    }
    // Check if the user has selected a level
    if (userLevel === "") {
    alert("Please select a level of study");
    }
    // Check if the user has specified at least one hour of study
    if (userHours === "") {
    if (isNaN(userHours) || userHours < 1) {
    alert("Please enter at least one hour of tuition.");
    return;
    }
    console.log({ userEmail, userLevel, userHours });
    });
    // Check if the number of hours requested is within the allowed range
    // Calculate the total cost
    // Display the total cost to the user
  4. Save your changes, and head across to your browser.

    Try submitting the form with an empty hours field, and then again with 0 or a negative number.

    In each case, should see the following alert message:

    Hourse validation

There are at least two more validation checks we need to consider:

  • Is the level of study selected by the user valid?
  • Is the number of hours requested within the allowed range for the level they have chosen (e.g., between 1 and 10 hours)?

In this tutorial, you learned how to validate user input in a sign-up form for Harmony Music Academy.

We have covered:

  • Presence checking to ensure that the user has entered data in all required fields.
  • Content validation to ensure that the data entered is of the correct type and format.
  • Using a return statement to stop the function from executing if any validation check fails.

In the next step, we will learn how to optimise the error messages shown to users when they fail to complete the required information.