JAVASCRIPT PROJECT 10

Build a JavaScript Form Validation

In this project, you will learn how to validate form inputs using JavaScript before allowing the form to be submitted.

01

Project Introduction

Form validation checks whether the information entered by a user is valid and complete.

What You Will Learn

  • HTML forms
  • Input values
  • Required field validation
  • Email validation
  • Password validation
  • Number validation
  • Regular expressions
  • DOM manipulation
  • preventDefault()
Input User enters information.
Validate JavaScript checks the information.
Submit Form submits only when valid.
02

Create the HTML Form

Start with a simple registration form containing name, email, password and age fields.

<form id="registrationForm">

    <input
        type="text"
        id="name"
        placeholder="Full Name"
    >

    <input
        type="email"
        id="email"
        placeholder="Email"
    >

    <input
        type="password"
        id="password"
        placeholder="Password"
    >

    <input
        type="number"
        id="age"
        placeholder="Age"
    >

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

</form>
The form element groups all related inputs and provides a submit event that JavaScript can control.
03

Add Error Message Elements

Create separate elements where validation errors can be displayed.

<span id="nameError"></span>

<span id="emailError"></span>

<span id="passwordError"></span>

<span id="ageError"></span>

JavaScript can update these elements whenever an input contains an error.

04

Get Form Values

Use getElementById() and the value property to read the information entered by the user.

const name =
    document.getElementById("name").value;

const email =
    document.getElementById("email").value;

const password =
    document.getElementById("password").value;

const age =
    document.getElementById("age").value;
Always read the current value when the form is submitted or when the input needs to be validated.
05

Validate Required Fields

The simplest validation is checking whether an input is empty.

if(name.trim() === ""){

    nameError.textContent =
        "Name is required.";

}

Why trim()?

trim() removes extra spaces from the beginning and end of a string.

const cleanName =
    name.trim();
06

Validate Email

A regular expression can be used to check whether an email has a basic valid structure.

const emailPattern =
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if(!emailPattern.test(email)){

    emailError.textContent =
        "Please enter a valid email.";

}
This checks the basic structure of an email address. It does not confirm that the mailbox actually exists.
07

Validate Password

A basic registration form can require a minimum password length.

if(password.length < 8){

    passwordError.textContent =
        "Password must contain at least 8 characters.";

}

Stronger Password Check

const strongPassword =
    /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;

if(!strongPassword.test(password)){

    passwordError.textContent =
        "Use at least 8 characters with letters and numbers.";

}
08

Validate Number

Convert the age value into a number and check whether it falls inside the required range.

const ageNumber =
    Number(age);

if(
    !ageNumber ||
    ageNumber < 18 ||
    ageNumber > 100
){

    ageError.textContent =
        "Enter an age between 18 and 100.";

}
09

Create Custom Validation

You can combine multiple validation rules to create a complete validation function.

function validateName(){

    const value =
        nameInput.value.trim();

    if(value === ""){

        return "Name is required.";

    }

    if(value.length < 3){

        return "Name must contain at least 3 characters.";

    }

    return "";

}
Returning an empty string means that no validation error was found.
10

Prevent Form Submission

The form normally submits when the user clicks the submit button. JavaScript can stop this behavior while validation is being performed.

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

        event.preventDefault();

    }
);

Why preventDefault()?

It prevents the browser's default form submission behavior, allowing JavaScript to validate the data first.

11

Display Error Messages

Error messages should clearly explain what the user needs to correct.

function showError(
    element,
    message
){

    element.textContent =
        message;

}

Clear Errors

function clearErrors(){

    nameError.textContent = "";

    emailError.textContent = "";

    passwordError.textContent = "";

    ageError.textContent = "";

}
Clear old errors before starting a new validation cycle.

Complete Project Flow

INPUT User Data
CHECK Validation
ERROR Show Message
VALID All Checks
SUBMIT Continue
13

Complete Form Validation Project

You have now learned how to read form values, validate required fields, check email structure, validate passwords, check numbers, show errors and control form submission.

Tutorial Completed! 📝

Now open the complete working Form Validation project and test the validation rules.

Run Complete Project Learn JavaScript Forms