Create Form Validation with HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create form validation using HTML, CSS, and JavaScript. This guide offers step-by-step instructions for a user-friendly web form.


create-form-validation-with-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Creating form validation is an essential part of web development. It ensures that users enter the correct information before submitting their forms. In this blog, we will guide you through the process of creating a simple form validation system using HTML, CSS, and JavaScript.

Prerequisites

Before you start, make sure you have:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A text editor (like Visual Studio Code, Sublime Text, or Notepad).
  • A web browser to test your code.

Source Code

Step 1 (HTML Code):

First, create an HTML file. We will build a simple registration form with fields for the username, email, and password, as well as a confirmation password.

Let's break down the HTML code step by step:

1. <!DOCTYPE html>

  • Declares the document type as HTML5, ensuring modern HTML rendering by the browser.

2. <html lang="en">

  • The <html> tag wraps the entire webpage content.
  • The lang="en" attribute indicates the page language is English, useful for accessibility and SEO.

3. <head> Section

The <head> contains meta-information, links, and configurations.

3.1 <meta charset="UTF-8">

  • Defines the character encoding as UTF-8, ensuring the page can display all standard symbols and text.

3.2 <meta name="viewport" content="width=device-width, initial-scale=1.0">

  • Ensures the webpage is responsive by controlling how it scales on different devices.
  • width=device-width: Makes the page fit the screen width.
  • initial-scale=1.0: Ensures no zoom is applied initially.

3.3 <title>JavaScript Form Validator</title>

  • Sets the page title displayed in the browser tab.

3.4 Google Fonts Link

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap">
  • Loads the Poppins font from Google Fonts, giving the form a modern look.

3.5 CSS Stylesheet Link

<link rel="stylesheet" href="styles.css">
  • Links an external CSS file (styles.css) for styling the form.

4. <body> Section

The <body> tag holds the visible content displayed on the webpage.

4.1 Form Container

<div class="form-container">
    <h2>Form Validator</h2>
    <form id="registrationForm">
  • The <div class="form-container"> acts as a wrapper for the form.
  • The <h2> tag displays the heading “Form Validator.”
  • <form id="registrationForm"> defines a form element and assigns it an id for easy reference by JavaScript.

4.2 Username Input Group

<div class="input-group">
    <input type="text" id="username" required placeholder=" ">
    <label for="username">Username</label>
    <span class="error" id="usernameError"></span>
</div>
  • Input Field: Collects the username.
    • type="text": Specifies it as a text field.
    • id="username": Assigns a unique ID for JavaScript to target.
    • required: Ensures the field cannot be left empty.
    • placeholder=" ": Empty placeholder to align the floating label style correctly.
  • Label: The <label> is associated with the input using for="username". It floats above the input when the user types.
  • Error Span: Displays validation errors (like “Username is too short”), with the id="usernameError" to target it dynamically.

4.3 Email Input Group

<div class="input-group">
    <input type="email" id="email" required placeholder=" ">
    <label for="email">Email</label>
    <span class="error" id="emailError"></span>
</div>
  • Similar structure as the username input, but the type="email" ensures the browser validates it as an email address.

4.4 Password Input Group

<div class="input-group">
    <input type="password" id="password" required placeholder=" ">
    <label for="password">Password</label>
    <span class="error" id="passwordError"></span>
</div>
  • Password Field: Uses type="password" to hide the input for privacy.
  • Displays a floating label and validation errors, if any.

4.5 Confirm Password Input Group

<div class="input-group">
    <input type="password" id="confirmPassword" required placeholder=" ">
    <label for="confirmPassword">Confirm Password</label>
    <span class="error" id="confirmPasswordError"></span>
</div>
  • This input ensures the user confirms their password by matching it with the first one.

4.6 Register Button

<button type="submit">Register</button>
  • A submit button to send the form data.
  • type="submit" triggers the form’s submission when clicked.

5. JavaScript Script Tag

<script src="script.js"></script>
  • Links the script.js file, where the form’s validation logic is implemented.
  • This file ensures the form behaves dynamically (like displaying errors if fields are invalid).

Step 2 (CSS Code):

Next, create a CSS file (styles.css) to style your form. This will enhance the appearance and make it more user-friendly.

Here’s a breakdown of the CSS code.

1. Global Styles (Universal Selector *)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'Poppins', sans-serif;
}
  • box-sizing: border-box;: Ensures padding and border are included in the element’s width and height, preventing unexpected layout shifts.
  • margin: 0; padding: 0;: Removes any default margin and padding for all elements.
  • font-family: 'Poppins', sans-serif;: Applies the Poppins font throughout the page for a clean, modern look.

2. Body Styling

body {
  background: linear-gradient(135deg, #74b9ff, #a29bfe);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
  • Background: A linear gradient blends two pastel colors at a 135-degree angle.
  • Height: The body spans the entire viewport height (100vh).
  • Flexbox Layout: Centers the form both horizontally and vertically with align-items and justify-content.

3. Form Container Styling

.form-container {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  text-align: center;
}
  • max-width: 400px;: Limits the form width to 400px for better readability.
  • Padding: Adds 30px padding inside the container.
  • border-radius: 15px;: Rounds the corners for a modern card-like design.
  • Box Shadow: Adds a subtle shadow for depth, creating a floating effect.

4. Heading Styling (h2)

h2 {
  margin-bottom: 20px;
  font-weight: 600;
  color: #333;
}
  • Font Weight: Makes the heading bold with 600.
  • Margin: Creates space below the heading to separate it from the form inputs.
  • Color: Uses dark gray (#333) for a clear, readable title.

5. Input Group Styling

.input-group {
  position: relative;
  margin-bottom: 25px;
  width: 100%;
}
  • Position: relative;: Allows positioning of the label inside the input.
  • margin-bottom: 25px;: Separates each input field for better spacing.

6. Input Field Styling

input {
  width: 100%;
  padding: 10px;
  padding-left: 10px;
  border: 1px solid #dfe6e9;
  border-radius: 8px;
  background: #f0f4f8;
  font-size: 16px;
  transition: border-color 0.3s;
}
  • width: 100%;: Ensures the input fills the available space.
  • Padding: Adds 10px padding for better usability.
  • Border: Light gray border (#dfe6e9).
  • Background: Light pastel background for a subtle design.
  • Font Size: Increases text size to 16px for readability.
  • transition: Smooth transition effect for the border color when focused.

7. Input Focus Effect

input:focus {
  outline: none;
  border-color: #74b9ff;
}
  • outline: none;: Removes the default blue outline on focus.
  • Border Color Change: Highlights the border in blue on focus (#74b9ff).

8. Floating Label Effect

label {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 16px;
  color: #aaa;
  transition: all 0.3s;
  pointer-events: none;
}
  • Absolute Positioning: Places the label over the input field.
  • Color: Light gray (#aaa) for inactive state.
  • Transition: Smoothly moves the label when the input is focused or filled.

9. Active/Focused Label Style

input:focus + label,
input:not(:placeholder-shown) + label {
  top: -10px;
  left: 8px;
  font-size: 12px;
  color: #74b9ff;
  background-color: #fff;
  padding: 0 5px;
}
  • When the input is focused or not empty, the label:
    • Moves above the input (top: -10px).
    • Shrinks to a 12px font size.
    • Turns blue to match the input border.
    • Gets a white background with 5px padding to avoid overlap with the input field.

10. Error Message Styling

.error {
  color: red;
  font-size: 0.85em;
  margin-top: 5px;
  display: none;
  text-align: left;
}
  • Color: Error messages are shown in red.
  • Font Size: Slightly smaller text (0.85em).
  • display: none;: Initially hides the error message. It will be shown via JavaScript.

11. Button Styling

button {
  width: 100%;
  padding: 10px;
  background-color: #0984e3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 10px;
}
  • Background Color: A vibrant blue (#0984e3).
  • Text Color: White text for contrast.
  • Border Radius: Rounded corners for a smooth look.
  • cursor: pointer;: Changes the cursor to a pointer on hover.
  • Transition: Smooth color change effect on hover.

12. Button Hover Effect

button:hover {
  background-color: #74b9ff;
}
  • On hover, the button background changes to light blue (#74b9ff).

13. Responsive Design (Media Query)

@media (max-width: 480px) {
  .form-container {
      width: 90%;
  }
}
  • On small screens (max width: 480px), the form container adjusts to 90% of the screen width, ensuring better usability on mobile devices.
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'Poppins', sans-serif;
}

body {
  background: linear-gradient(135deg, #74b9ff, #a29bfe);
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-container {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  text-align: center;
}

h2 {
  margin-bottom: 20px;
  font-weight: 600;
  color: #333;
}

.input-group {
  position: relative;
  margin-bottom: 25px;
  width: 100%;
}

input {
  width: 100%;
  padding: 10px;
  padding-left: 10px;
  border: 1px solid #dfe6e9;
  border-radius: 8px;
  background: #f0f4f8;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #74b9ff;
}

label {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 16px;
  color: #aaa;
  transition: all 0.3s;
  pointer-events: none;
}

input:focus + label,
input:not(:placeholder-shown) + label {
  top: -10px;
  left: 8px;
  font-size: 12px;
  color: #74b9ff;
  background-color: #fff;
  padding: 0 5px;
}

.error {
  color: red;
  font-size: 0.85em;
  margin-top: 5px;
  display: none;
  text-align: left;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #0984e3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: 10px;
}

button:hover {
  background-color: #74b9ff;
}

@media (max-width: 480px) {
  .form-container {
      width: 90%;
  }
} 

Step 3 (JavaScript Code):

Now, create a JavaScript file (script.js) to handle the form validation logic.

Here’s a breakdown of the JavaScript code.

1. Event Listener for Form Submission

document.getElementById("registrationForm").addEventListener("submit", function (event) {
  event.preventDefault();
  clearErrors();
  const username = document.getElementById("username").value.trim();
  const email = document.getElementById("email").value.trim();
  const password = document.getElementById("password").value.trim();
  const confirmPassword = document.getElementById("confirmPassword").value.trim();

  let isValid = true;
  • addEventListener("submit", ...): Listens for the form's submit event.
  • event.preventDefault(): Prevents the form from refreshing the page upon submission.
  • clearErrors(): Clears any previously displayed error messages before validating the form.
  • trim(): Removes leading and trailing spaces from the input values to avoid accidental whitespace errors.
  • let isValid = true;: A flag to track if the form inputs are valid. If any field fails validation, this will be set to false.

2. Username Validation

const usernamePattern = /^[a-zA-Z0-9]+$/;
if (username.length < 3 || !usernamePattern.test(username)) {
    showError("usernameError", "Username must be at least 3 characters long and contain only letters and numbers.");
    isValid = false;
}
  • Pattern: Ensures the username contains only letters and numbers (a-z, A-Z, 0-9).
  • Length Check: If the username is shorter than 3 characters or contains invalid characters, an error is shown.
  • isValid = false: Marks the form as invalid if the username is incorrect.

3. Email Validation

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
    showError("emailError", "Please enter a valid email address.");
    isValid = false;
}
  • Pattern: This regular expression checks if the email contains:
    • At least one character before and after the @.
    • A . after the domain name.
  • If the email is invalid, the showError() function displays the error.

4. Password Validation

const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
if (!passwordPattern.test(password)) {
    showError("passwordError", "Password must be at least 8 characters long, with 1 uppercase, 1 lowercase, and 1 number.");
    isValid = false;
}
  • Pattern: Checks that the password:
    • Is at least 8 characters long.
    • Contains at least one uppercase letter, one lowercase letter, and one number.
  • If the password doesn’t meet these criteria, the appropriate error message is shown.

5. Confirm Password Validation

if (password !== confirmPassword) {
    showError("confirmPasswordError", "Passwords do not match.");
    isValid = false;
}
  • Ensures the password and confirm password fields match.
  • If they don’t, an error message is displayed.

6. Success Message

if (isValid) {
    alert("Registration successful!");
}
  • If all validations pass (isValid === true), a success message is displayed using alert().

7. Clear Errors Function

function clearErrors() {
  document.querySelectorAll(".error").forEach(error => {
      error.style.display = "none";
      error.innerText = "";
  });
}
  • querySelectorAll(".error"): Selects all elements with the class error.
  • forEach: Loops through each error element and:
    • Hides the error (style.display = "none").
    • Clears the error message (innerText = "").

8. Show Error Function

function showError(elementId, message) {
  const errorElement = document.getElementById(elementId);
  errorElement.innerText = message;
  errorElement.style.display = "block";
}
  • getElementById(): Selects the error element by its ID (e.g., usernameError).
  • innerText: Sets the error message to be displayed.
  • style.display = "block": Makes the error visible.
document.getElementById("registrationForm").addEventListener("submit", function (event) {
  event.preventDefault();
  clearErrors();
  const username = document.getElementById("username").value.trim();
  const email = document.getElementById("email").value.trim();
  const password = document.getElementById("password").value.trim();
  const confirmPassword = document.getElementById("confirmPassword").value.trim();

  let isValid = true;

  const usernamePattern = /^[a-zA-Z0-9]+$/;
  if (username.length < 3 || !usernamePattern.test(username)) {
      showError("usernameError", "Username must be at least 3 characters long and contain only letters and numbers.");
      isValid = false;
  }

  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailPattern.test(email)) {
      showError("emailError", "Please enter a valid email address.");
      isValid = false;
  }

  const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
  if (!passwordPattern.test(password)) {
      showError("passwordError", "Password must be at least 8 characters long, with 1 uppercase, 1 lowercase, and 1 number.");
      isValid = false;
  }

  if (password !== confirmPassword) {
      showError("confirmPasswordError", "Passwords do not match.");
      isValid = false;
  }

  if (isValid) {
      alert("Registration successful!");
  }
});

function clearErrors() {
  document.querySelectorAll(".error").forEach(error => {
      error.style.display = "none";
      error.innerText = "";
  });
}

function showError(elementId, message) {
  const errorElement = document.getElementById(elementId);
  errorElement.innerText = message;
  errorElement.style.display = "block";
}

Final Output:

create-form-validation-with-html-css-and-javascript.gif

Conclusion:

In this blog, you learned how to create a simple form validation system using HTML, CSS, and JavaScript. Form validation is crucial for ensuring users provide accurate information. By following this guide, you can enhance your web applications, making them more user-friendly and secure.

Feel free to expand on this basic validation system by adding more fields or custom rules to suit your needs!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺