Client-Side Form Validation Using Vanilla JavaScript


Most web applications nowadays will require you to fill out a form at some point, be it an online banking application or a music streaming service.

And because end users are never to be trusted, we need to fool-proof our application so that it detects when the input is incorrect and returns it back to the user with an appropriate (error) message.

Form validation is a technique used to prevent users from providing data that does not meet the requirements of the application. An example would be making sure that the provided password has at least one uppercase character and a number. You can validate data on the server-side, or the client-side.

Server-side validation is the idea of validating user data after it is sent to the servers. If the data is not in the expected format, it is sent back to the user.

On the other hand, client-side validation entails validating the data input by the user in the browser before it is sent to the server. This is typically more efficient than server-side validation since it prevents the round trip from the client to server and back. It's also an early filter, which makes sure that the right data gets through, instead of dealing with the wrong data once it has been passed through.

This doesn't mean that the server shouldn't have data validation - we're just sifting through initially now.

In this tutorial, we will discuss how we can validate data in the browser using vanilla JavaScript.

Creating a Form

Let's make a simple sign-up form, which will will consist of the following fields:

  1. username
  2. first-password - used to check the initial password for certain criteria
  3. second-password - used as confirmation, and making sure the user didn't make a typo in the first-password field.

... and put it into our index.html file:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <script defer src="validate.js"></script>

    <title>Form Validation</title>
    <h1>Form Validation Using JavaScript</h1>

    <form id="form" action="/" method="GET">
      <!-- We are only interested in client-side validation now -->

      <!-- All the fields are required -->
        <label for="username">Username: </label>
        <input type="text" name="username" id="username" autofocus required />

        <label for="first-password">Password: </label>

        <label for="second-password">Confirm Password: </label>

      <button type="submit">Submit</button>

    <div id="show-error">No validation error yet!</div>
    <!--We will use this div to display validation error -->

This HTML file will render a simple form which looks like this:


Before writing any code, let's first go over the list of validations we need:

  • Make sure the username starts with an uppercase letter
  • The username must have at least one digit included
  • Ensure the password length is between 8 to 20 characters
  • Make sure the password contains at least one uppercase letter
  • Confirm the two passwords match

In case the user input isn't compliant with the requirements above, we want:

  • The text of the last div to change
  • Prevent the form from submitting


First, let's make a script file validate.js and link it with our index.html file inside our head tag:

<script defer src="validate.js"></script>

Then, let's access the relevant fields from the document:

// To disable the form from submitting
const form = document.querySelector('#form');
// To display the error message
const errorDiv = document.querySelector('#show-error');
// To validate the username
const username = document.querySelector('#username');
// To validate the password
const firstPassword = document.querySelector('#first-password');
// To confirm the password
const secondPassword = document.querySelector('#second-password'); 

For the sake of simplicity, let's make it so that the form validations are only run upon clicking the submit button, and not in real-time:

form.addEventListener('submit', (error) => {
     // All validation checks are run in this method.   

Implementing the Validators

First Letter of the Username is Uppercase

This is pretty self explanatory, if the string's first letter is the same as its uppercase variant, it means that username in fact starts with an uppercase letter:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

// We will include any and all errors in this string
let incorrectInput = '';

const firstLetter = username.value[0];

// Return true if first letter is uppercase
const firstLetterIsUpperCase = (firstLetter === firstLetter.toUpperCase()); 

if (!firstLetterIsUpperCase) {
    incorrectInput += ' The first letter of username must be uppercase.\n';

Username Contains at Least One Digit

/\d/ is a regular expression pattern that matches to a single digit, meaning if it matches even once inside the provided username, the username contains a digit:

// Regex to see if a digit is in the username, returns true if there is
const usernameIncludesDigit = /\d/.test(username.value); 

if (!usernameIncludesDigit) {
    incorrectInput += 'Username must include at least one digit.\n';

Password is Between 8 and 20 Characters Long

The length string attribute should give us the number of characters in the password. A simple conditional statement should do the trick:

const badPasswordLength = (firstPassword.value.length < 8 || firstPassword.value.length > 20);

if (badPasswordLength) {
    incorrectInput += ' The password should be within 8 to 20 characters.\n';

Password Contains at Least One Uppercase Character

This is similar to what we did for username. We just need to modify the regular expression to check for uppercase letters instead of digits:

// Regex to see if a digit is in the username, returns true if there is
const passwordIncludesUppercase = /[a-z]/.test(firstPassword.value); 

if (!passwordIncludesUppercase) {
    incorrectInput += ' The password should contain at least one uppercase character.\n';

Verify that the Two Passwords are the Same

Finally, we need to compare firstPassword to secondPassword to see if they match:

if (firstPassword.value !== secondPassword.value) {
    incorrectInput += 'The passwords do not match.\n';

Displaying the Error Messages

After all these checks, if any condition is unsatisfied, incorrectInput will not be an empty string and will contain the issue raised in that conditional block.

In this case, we will change the text in errorDiv to show our errors in red:

if (incorrectInput !== "") {
    // Change the error div tag to display the error message(s)
    errorDiv.innerText = incorrectInput; 
    // Change the color of the text to red = 'red'; 
    // Prevent the form button from submitting again, before fixing the issues

Testing the Code

And now, let's test out our new form with the following input:

  • Username: johndoe
  • Password: 42
  • Confirm Password: 421

Which should yield the following results:


In this article we used vanilla JavaScript to validate a simple HTML form.

JavaScript enabled us to define custom validation checks that fit our use case. For example, you can add custom patterns that a password must meet in order for a user to sign up on your website.

Last Updated: February 24th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.