Form Validation in HTML CSS & JavaScript

When you fill out the form on websites, you often come across messages that things like “Please enter a valid email address” or “Password must be at least 8 characters long.” These messages are part of form validation, which is important for making sure information you enter is correct and useful. 

Types of Form Validation

Important fields required like email address and password are filling out before submitting the form.

Formats check like verifying the data follows a specific format, such as valid email address or phone number.

Checking of Lengths, setting limits on how long or short certain fields can be, such a password needs to be a minimum number of characters.

Comparison checks, to ensure that data matches other data, such as checking if passwords match when account creation.

This blog post is design to guide the process of For Validation using HTML CSS, and JavaScript. Additionally, you’ll also learn how to show or hide password visibility upon toggle button click.

To Start codes for Form Validation

Let’s create a folder and named it whatever you want and then create these below 4 (four) files inside in it.

1. index.html   2. thank-you.html   3. style.css   4. script.js

Now add the below HTML codes to your index.html file to create basic structure of layout.

<!DOCTYPE html>
<!-- Website - www.codingjasimweb.com -->
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation | Coding Jasim</title>
    <link rel="stylesheet" href="style.css">
    <!-- Fontawesome CDN Link For Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
  </head>
  <body>
    <form action="thank-you.html">
      <h2>Form Validation</h2>
      <div class="form-group fullname">
        <label for="fullname">Full Name</label>
        <input type="text" id="fullname" placeholder="Enter your full name">
      </div>
      <div class="form-group email">
        <label for="email">Email Address</label>
        <input type="text" id="email" placeholder="Enter your email address">
      </div>
      <div class="form-group password">
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter your password">
        <i id="pass-toggle-btn" class="fa-solid fa-eye"></i>
      </div>
      <div class="form-group date">
        <label for="date">Birth Date</label>
        <input type="date" id="date" placeholder="Select your date">
      </div>
      <div class="form-group gender">
        <label for="gender">Gender</label>
        <select id="gender">
          <option value="" selected disabled>Select your gender</option>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
          <option value="Other">Other</option>
        </select>
      </div>
      <div class="form-group submit-btn">
        <input type="submit" value="Submit">
      </div>
    </form>

    <script src="script.js"></script>
  </body>
</html>

Next add the following HTML codes to you thank-you.html. When the users fill out the form with essential information, then they will redirected to this HTML page. This page contains a heading only as “Thank’s for filling out of the form correctly”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thanks page</title>
</head>
<body>
    <h1>Thank's for filling out the form correctly.</h1>
</body>
</html>

Now Next, add the following CSS code to style.css file, through which you can design the form beautiful. As per your choice, you can customize this form by using CSS properties like color, fonts, size, and others.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;500;600;700&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Open Sans', sans-serif;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 0 10px;
  background: #501bb2;
}

form {
  padding: 25px;
  background: #fff;
  max-width: 500px;
  width: 100%;
  border-radius: 7px;
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.05);
}

form h2 {
  font-size: 27px;
  text-align: center;
  margin: 0px 0 30px;
}

form .form-group {
  margin-bottom: 15px;
  position: relative;
}

form label {
  display: block;
  font-size: 15px;
  margin-bottom: 7px;
}

form input,
form select {
  height: 45px;
  padding: 10px;
  width: 100%;
  font-size: 15px;
  outline: none;
  background: #f8f7f7;
  border-radius: 3px;
  border: 1px solid #bfbfbf;
}

form input:focus,
form select:focus {
  border-color: #9a9a9a;
}

form input.error,
form select.error {
  border-color: #f91919;
  background: #f9f0f1;
}

form small {
  font-size: 14px;
  margin-top: 5px;
  display: block;
  color: #f91919;
}

form .password i {
  position: absolute;
  right: 0px;
  height: 45px;
  top: 28px;
  font-size: 13px;
  line-height: 45px;
  width: 45px;
  cursor: pointer;
  color: #939393;
  text-align: center;
}

.submit-btn {
  margin-top: 30px;
}

.submit-btn input {
  color: white;
  border: none;
  height: auto;
  font-size: 16px;
  padding: 13px 0;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
  text-align: center;
  background: #1385e2;
  transition: 0.2s ease;
}

.submit-btn input:hover {
  background: #a0bfb9;
}

Finally, add the below JavaScript code to your Script.js file, to enable form validation, display error messages appropriately, and implementation of toggle function for password visibility.

// Input & form selection
const form = document.querySelector("form");
const passwordInput = document.getElementById("password");
const passToggleBtn = document.getElementById("pass-toggle-btn");

// Display error messages by this function
const showError = (field, errorText) => {
    field.classList.add("error");
    const errorElement = document.createElement("small");
    errorElement.classList.add("error-text");
    errorElement.innerText = errorText;
    field.closest(".form-group").appendChild(errorElement);
}

// Fandle form submission by this function
const handleFormData = (e) => {
    e.preventDefault();

    // Retrie inputs
    const fullnameInput = document.getElementById("fullname");
    const emailInput = document.getElementById("email");
    const dateInput = document.getElementById("date");
    const genderInput = document.getElementById("gender");

    // Trimming of values from input fields
    const fullname = fullnameInput.value.trim();
    const email = emailInput.value.trim();
    const password = passwordInput.value.trim();
    const date = dateInput.value;
    const gender = genderInput.value;

    // Regular expression pattern for email validation
    const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

    // Previous error messages clearence
    document.querySelectorAll(".form-group .error").forEach(field => field.classList.remove("error"));
    document.querySelectorAll(".error-text").forEach(errorText => errorText.remove());

    // Perform validation checks
    if (fullname === "") {
        showError(fullnameInput, "Enter your full name");
    }
    if (!emailPattern.test(email)) {
        showError(emailInput, "Enter a valid email address");
    }
    if (password === "") {
        showError(passwordInput, "Enter your password");
    }
    if (date === "") {
        showError(dateInput, "Select your date of birth");
    }
    if (gender === "") {
        showError(genderInput, "Select your gender");
    }

    // Checking of any remaining errors before form submission
    const errorInputs = document.querySelectorAll(".form-group .error");
    if (errorInputs.length > 0) return;

    // Form Submittion
    form.submit();
}

// Toggling of password visibility
passToggleBtn.addEventListener('click', () => {
    passToggleBtn.className = passwordInput.type === "password" ? "fa-solid fa-eye-slash" : "fa-solid fa-eye";
    passwordInput.type = passwordInput.type === "password" ? "text" : "password";
});

// Form submission event
form.addEventListener("submit", handleFormData);

In Conclusion, through this blog post you learn about Form Validation’s fundamental aspects that enhances user experience and input data accuracy. By implementing validation techniques, websites ensures that the information they collect is reliable, secure, and error-free.

If you experience any challenges or errors while building a form or if the code isn’t functioning as anticipated, you can obtain the source code files at no cost by clicking the download button below:

Scroll to Top