Forms are essential in web development, allowing users to submit data. Form validation is integral to this process and must ensure the accuracy and integrity of user input.
Form validation is the practice of verifying that data entered by individuals meets certain criteria and is accurate. Its primary goal is to prevent incomplete or inaccurate form submissions.
This blog aims to guide novice web developers through the validation process using HTML, CSS and JavaScript. Starting from scratch, we will teach how to build responsive forms using these technologies before diving deeper into form validation using JavaScript.
Discover how to easily hide or show password visibility using the toggle button, scrolling to the bottom of this page, and clicking the View Live Demo link.

How to Implement Form Validation in HTML

Follow these step-by-step instructions to create a JavaScript form using HTML, CSS and vanilla JavaScript.

  • Establish a new folder. Add files to this new directory, giving it any name you wish.
  • Create an index.html file.
  • Thank-you.html is an index file you can create with an extension.html.
  • Create a file named style.css with this name as its file extension.
  • Create a file named script.js. The file should have its name prefixed with “script.js”.

Add this HTML code to your index.html file to create a basic form layout. It includes fields for full name, email address, password, date of birth, and gender of birth, as well as additional fields that you may add or delete as necessary.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation in HTML</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>
        <label for="fullname">Full Name</label>
        <input type="text" id="fullname" placeholder="Enter your full name">
      </div>
      <div>
        <label for="email">Email Address</label>
        <input type="text" id="email" placeholder="Enter your email address">
      </div>
      <div>
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter your password">
        <i id="pass-toggle-btn"></i>
      </div>
      <div>
        <label for="date">Birth Date</label>
        <input type="date" id="date" placeholder="Select your date">
      </div>
      <div>
        <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>
        <input type="submit" value="Submit">
      </div>
    </form>
    <script src="script.js"></script>
  </body>
</html>

Add these HTML codes to your thank-you.html page: When the user submits their form correctly, they’ll be taken directly to this HTML webpage, which only has one heading that says: “Thanks for filling out your form accurately!”

<!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 you for filling out the form correctly.</h1>
</body>
</html>

Add these CSS codes to your style.css file to style and make your form visually pleasing and responsive. You can tailor these codes by changing the font, colour, and size settings to meet your needs.

@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;
  padding: 0 10px;
  min-height: 100vh;
  background: #1BB295;
}
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: #fff;
  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: #1BB295;
  transition: 0.2s ease;
}
.submit-btn input:hover {
  background: #179b81;
}

Add this JavaScript code to your script.js file to activate form validation, display appropriate error messages, and implement toggle functionality to make passwords visible.

// Selecting form and input elements
const form = document.querySelector("form");
const passwordInput = document.getElementById("password");
const passToggleBtn = document.getElementById("pass-toggle-btn");
// Function to display error messages
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);
}
// Function to handle form submission
const handleFormData = (e) => {
    e.preventDefault();
    // Retrieving input elements
    const fullnameInput = document.getElementById("fullname");
    const emailInput = document.getElementById("email");
    const dateInput = document.getElementById("date");
    const genderInput = document.getElementById("gender");
    // Getting trimmed 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}$/;
    // Clearing previous error messages
    document.querySelectorAll(".form-group .error").forEach(field => field.classList.remove("error"));
    document.querySelectorAll(".error-text").forEach(errorText => errorText.remove());
    // Performing 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 for any remaining errors before form submission
    const errorInputs = document.querySelectorAll(".form-group .error");
    if (errorInputs.length > 0) return;
    // Submitting the form
    form.submit();
}
// Toggling 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";
});
// Handling form submission event
form.addEventListener("submit", handleFormData);

Final Words and Conclusion

We started by creating the structure of our form in HTML, which included outlining its input fields and attributes as well as any required elements. Then, we used CSS to style elements such as form fields, buttons, and labels before using JavaScript for validation logic to ensure users enter only valid data into our form.
Following the instructions here, your form should be functional and possess validation features. I encourage you to experiment and explore the variety of forms available here to enhance your web development abilities.
Clicking the Download button allows you to quickly and freely access this form’s source files in case you encounter any difficulties creating your form or your code misbehaves as expected. Click View Live for an online demonstration.

One Reply to “How to Implement Form Validation in HTML CSS and JavaScript”

  • Www.evernote.com
    Www.evernote.com
    Reply

    I’m amazed by how much I learned from this tutorial. Your approach to explaining form validation is both educational and engaging. Looking forward to more tutorials from you!

Leave a Reply

Your email address will not be published. Required fields are marked *