Day-7 of Learning JavaScript: The Guardian of Good Data: A Beginner’s Guide to Form Validation with JavaScript
Published: 2024-01-10 12:06:10

Greetings, curious minds! Today, we embark on an expedition into the magical realm of form validation, armed with JavaScript spells to make your web forms smarter and user-friendly. Form validation may sound daunting, but fear not! By the end of this journey, you’ll wield the power to check if fields are filled, validate email formats, and provide friendly error messages. So, tighten your laces and let’s dive into the captivating world of interactive form validation!

## What is Form Validation?
In the digital kingdom, form validation is like a wise gatekeeper ensuring that the information submitted through a web form is accurate, complete, and sensible. It’s the guardian of your website, preventing chaos and ensuring a smooth interaction between users and your digital domain.

## Why Do We Need It?
Imagine a world without form validation — a world where users can submit empty forms, provide gibberish emails, and wreak havoc on your data. Form validation saves us from this chaos, offering a shield against incomplete or inaccurate inputs. It ensures that the data collected is reliable, making both users and website owners happy campers.

---

**Let’s get started!**

## Creating the HTML structure
First, we need to create the HTML structure of our form. We will use a <form> element to wrap our input fields and a submit button. We will also use some <label> and <span> elements to display the field names and error messages.

<br>
**Here is the HTML code for our form:**

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Form Validation</title>
    <link rel="stylesheet" href="styles.css"> <!-- A place for styling, if needed -->
</head>
<body>

    <form id="myForm" onsubmit="return validateForm()">

      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" id="name" name="name" />
        <span id="nameError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="email">Email</label>
        <input type="email" id="email" name="email" />
        <span id="emailError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" id="password" name="password" />
        <span id="passwordError" class="error"></span>
      </div>

      <div class="form-group">
        <label for="confirmPassword">Confirm Password</label>
        <input type="password" id="confirmPassword" name="confirmPassword" />
        <span id="confirmPasswordError" class="error"></span>
      </div>

      <div class="form-group">
        <button type="submit">Register</button>
      </div>

    </form>

    <script src="script.js"></script> <!-- Our JavaScript spellbook -->
</body>
</html>
```
<br>
**Let’s explain what we did here:**

- We gave our form an id of `myForm` and added an `onsubmit` attribute that calls a JavaScript function named `validateForm`. This function will perform the validation logic and return either `true` or `false` depending on the result. If the function returns `true`, the form will be submitted to the server. If the function returns `false`, the form will not be submitted and the user will see the error messages.

- We used `<div>` elements with a class of `form-group` to group each input field and its label and error message. This will help us to style and position them later with CSS.

- We used `<label>` elements with a `for` attribute that matches the `id` of the corresponding input field. This will make the label clickable and improve the accessibility of our form.

- We used `<input>` elements with different `type` attributes to create different types of input fields. For example, we used `type="text"` for the name field, `type="email"` for the email field, and `type="password"` for the password fields. The `type` attribute will affect how the browser displays and validates the input field. For example, the browser will automatically check if the email field has a valid email format and hide the characters in the password fields.

- We gave each input field a `name` attribute that will be used to identify the data when the form is submitted to the server. The `name` attribute should be unique and descriptive for each input field.

- We used `<span>` elements with a class of `error` and an id that matches the input field name with an `Error` suffix. For example, we used `id="nameError"` for the name field error message. These elements will be used to display the error messages if the input field is invalid. We will use JavaScript to change the content and visibility of these elements.

---

## Styling the form with CSS
Next, we need to style our form with CSS to make it look more appealing and user-friendly. We will use some basic CSS properties to change the colors, fonts, borders, margins, and paddings of our elements. We will also use some CSS pseudo-classes to change the appearance of our input fields when they are focused or invalid.

**Here is the CSS code for our form:**

```
/* Select the form element and set its width, margin, and font */
form {
  width: 400px;
  margin: 20px auto;
  font-family: Arial, sans-serif;
}

/* Select the form-group elements and set their margin and padding */
.form-group {
  margin: 10px 0;
  padding: 10px;
}

/* Select the label elements and set their display, font-weight, and margin */
label {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
}

/* Select the input elements and set their display, width, padding, border, and outline */
input {
  display: block;
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  outline: none;
}

/* Select the input elements when they are focused and change their border color */
input:focus {
  border-color: #66a3ff;
}

/* Select the input elements when they are invalid and change their border color */
input:invalid {
  border-color: #ff6666;
}

/* Select the error elements and set their display, color, and margin */
.error {
  display: none;
  color: #ff6666;
  margin-top: 5px;
}

/* Select the button element and set its display, width, padding, border, background, color, cursor, and outline */
button {
  display: block;
  width: 100%;
  padding: 10px;
  border: none;
  background: #66a3ff;
  color: #fff;
  cursor: pointer;
  outline: none;
}

/* Select the button element when it is hovered and change its background color */
button:hover {
  background: #3399ff;
}
```

<br>
**Let’s explain what we did here:**

- We selected the `form` element and set its width to 400 pixels, its margin to 20 pixels auto (which means 20 pixels top and bottom, and auto left and right to center the form), and its font-family to Arial, sans-serif (which means Arial if available, or any sans-serif font as a fallback).

- We selected the `.form-group` elements (which means the elements with a class of `form-group`) and set their margin to 10 pixels top and bottom, and their padding to 10 pixels all around. This will create some space between and inside the form groups.

- We selected the `label` elements and set their display to block (which means they will take up the whole width of their parent element), their font-weight to bold (which means they will have thicker text), and their margin-bottom to 5 pixels. This will make the labels stand out and create some space below them.

- We selected the `input` elements and set their display to block (which means they will take up the whole width of their parent element), their width to 100% (which means they will take up the whole width of their parent element), their padding to 10 pixels (which means they will have some space inside them), their border to 1 pixel solid #ccc (which means they will have a thin gray border), and their outline to none (which means they will not have a blue outline when they are focused). This will make the input fields look consistent and neat.

- We selected the `input` elements when they are focused (which means when the user clicks or tabs on them) and changed their border-color to #66a3ff (which means a light blue color). This will make the input fields look more interactive and highlight the current field.

- We selected the `input` elements when they are invalid (which means when they do not meet the validation criteria) and changed their border-color to #ff6666 (which means a light red color). This will make the input fields look more noticeable and indicate the error.

- We selected the `.error` elements (which means the elements with a class of `error`) and set their display to none (which means they will be hidden by default), their color to #ff6666 (which means a light red color), and their margin-top to 5 pixels. This will make the error messages look consistent and create some space above them.

- We selected the `button` element and set its display to block (which means it will take up the whole width of its parent element), its width to 100% (which means it will take up the whole width of its parent element), its padding to 10 pixels (which means it will have some space inside it), its border to none (which means it will not have a border), its background to #66a3ff (which means a light blue color), its color to #fff (which means white), its cursor to pointer (which means it will change to a hand icon when hovered), and its outline to none (which means it will not have a blue outline when focused). This will make the button look attractive and clickable.

- We selected the `button` element when it is hovered (which means when the user moves the mouse over it) and changed its background color to #3399ff (which means a darker blue color). This will make the button look more interactive and responsive.

---

## Writing the JavaScript logic
Finally, we need to write the JavaScript logic to validate the form data and display the error messages. We will use some built-in methods and properties of the HTML DOM (Document Object Model) to access and manipulate the form elements. We will also use some regular expressions to check the email format.

**Here is the JavaScript code for our form validation:**

```
// Get the form element by its id
var form = document.getElementById("myForm");

// Add an event listener to the form's submit event
form.addEventListener("submit", function(event) {
  // Prevent the default behavior of the form submission
  event.preventDefault();

  // Get the input elements by their ids
  var name = document.getElementById("name");
  var email = document.getElementById("email");
  var password = document.getElementById("password");
  var confirmPassword = document.getElementById("confirmPassword");

  // Get the error elements by their ids
  var nameError = document.getElementById("nameError");
  var emailError = document.getElementById("emailError");
  var passwordError = document.getElementById("passwordError");
  var confirmPasswordError = document.getElementById("confirmPasswordError");

  // Initialize a variable to store the validation status
  var isValid = true;

  // If the validation status is true, submit the form to the server
  if (isValid) {
    // Create an alert message that says "All the data is correct"
    alert("All the data is correct");
    // Submit the form to the server
    form.submit();
  }

  // Check if the name field is empty
  if (name.value === "") {
    // Set the error message
    nameError.textContent = "Name is required";
    // Show the error element
    nameError.style.display = "block";
    // Set the validation status to false
    isValid = false;
  } else {
    // Clear the error message
    nameError.textContent = "";
    // Hide the error element
    nameError.style.display = "none";
  }

  // Check if the email field is empty or has an invalid format
  // Use a regular expression to test the email format
  var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  if (email.value === "" || !emailRegex.test(email.value)) {
    // Set the error message
    emailError.textContent = "Email is required and must be valid";
    // Show the error element
    emailError.style.display = "block";
    // Set the validation status to false
    isValid = false;
  } else {
    // Clear the error message
    emailError.textContent = "";
    // Hide the error element
    emailError.style.display = "none";
  }

  // Check if the password field is empty or has less than 6 characters
  if (password.value === "" || password.value.length < 6) {
    // Set the error message
    passwordError.textContent = "Password is required and must be at least 6 characters long";
    // Show the error element
    passwordError.style.display = "block";
    // Set the validation status to false
    isValid = false;
  } else {
    // Clear the error message
    passwordError.textContent = "";
    // Hide the error element
    passwordError.style.display = "none";
  }

  // Check if the confirm password field is empty or does not match the password field
  if (confirmPassword.value === "" || confirmPassword.value !== password.value) {
    // Set the error message
    confirmPasswordError.textContent = "Confirm password is required and must match the password";
    // Show the error element
    confirmPasswordError.style.display = "block";
    // Set the validation status to false
    isValid = false;
  } else {
    // Clear the error message
    confirmPasswordError.textContent = "";
    // Hide the error element
    confirmPasswordError.style.display = "none";
  }

  // If the validation status is true, submit the form to the server
  if (isValid) {
    form.submit();
  }
});

```

<br>
**Let’s explain what we did here:**

- We got the form element by its id using the `document.getElementById` method. This method returns a reference to the element with the specified id in the document.

- We added an event listener to the form’s submit event using the `addEventListener` method. This method attaches a function to be executed when the specified event occurs on the element. The first parameter is the name of the event, and the second parameter is the function to be executed. The function takes an event object as a parameter, which contains information and methods related to the event.

- We prevented the default behavior of the form submission using the `event.preventDefault` method. This method stops the browser from performing the default action of the event, which in this case is submitting the form to the server. We did this because we want to validate the form data before sending it to the server.

- We got the input elements by their ids using the `document.getElementById` method. These elements have some properties and methods that we can use to access and manipulate their values and attributes. For example, we can use the value property to get or set the `value` of the input element, and the `type` property to get the type of the input element.

- We got the error elements by their ids using the `document.getElementById` method. These elements have some properties and methods that we can use to change their content and style. For example, we can use the `textContent` property to get or set the text content of the element, and the `style` property to access and modify the CSS style of the element.

- We initialized a variable named `isValid` to store the validation status. We set its initial value to `true`, and we will change it to `false` if any of the input fields is invalid.

- We checked if the name field is empty using the `===` operator, which compares the values and types of the operands. If the name field is empty, we set the error message using the `textContent` property of the name error element, we showed the error element using the `style.display` property and setting it to `"block"`, and we set the validation status to `false` using the `=` operator, which assigns the value of the right operand to the left operand. If the name field is not empty, we cleared the error message using the `textContent` property of the name error element, and we hid the error element using the `style.display` property and setting it to `"none"`.

- We checked if the email field is empty or has an invalid format using the `===` operator and the `!` operator, which negates the value of the operand. We also used a regular expression to test the email format using the `test` method, which returns `true` if the string matches the pattern, and `false` otherwise. A regular expression is a sequence of characters that defines a search pattern. We used the following regular expression to check the email format: `/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/`. This means that the email should start with one or more alphanumeric characters, dots, underscores, or hyphens, followed by an `@` sign, followed by one or more alphanumeric characters, dots, or hyphens, followed by a dot, followed by two to four alphabetic characters. If the email field is empty or has an invalid format, we set the error message using the `textContent` property of the email error element, we showed the error element using the `style.display` property and setting it to `"block"`, and we set the validation status to `false` using the `=` operator. If the email field is not empty and has a valid format, we cleared the error message using the `textContent` property of the email error element, and we hid the error element using the `style.display` property and setting it to `"none"`.

- We checked if the password field is empty or has less than 6 characters using the `===` operator and the `<` operator, which compares the values of the operands. We also used the `length` property of the string to get the number of characters in the password. If the password field is empty or has less than 6 characters, we set the error message using the `textContent` property of the password error element, we showed the error element using the `style.display` property and setting it to `"block"`, and we set the validation status to `false` using the `=` operator. If the password field is not empty and has at least 6 characters, we cleared the error message using the `textContent` property of the password error element, and we hid the error element using the `style.display` property and setting it to `"none"`.

- We checked if the confirm password field is empty or does not match the password field using the `===` operator and the `!==` operator, which compares the values and types of the operands. If the confirm password field is empty or does not match the password field, we set the error message using the `textContent` property of the confirm password error element, we showed the error element using the `style.display` property and setting it to `"block"`, and we set the validation status to false using the `=` operator. If the confirm password field is not empty and matches the password field, we cleared the error message using the `textContent` property of the confirm password error element, and we hid the error element using the `style.display` property and setting it to `"none"`.

- We checked if the validation status is `true` using the `if` statement, which executes a block of code if the condition is `true`. If the validation status is `true`, we submitted the form to the server using the `submit` method of the form element. This method sends the form data to the specified action URL using the specified method.

---

## What we learned
In this article, we learned how to implement basic form validation using JavaScript. We learned how to:

- Create the HTML structure of our form using `<form>`, `<label>`, `<input>`, `<span>`, and `<button>` elements.

- Style our form with CSS using properties like `width`, `margin`, `padding`, `border`, `background`, `color`, `display`, `font-weight`, and `cursor`.

- Use CSS pseudo-classes like `:focus` and `:invalid` to change the appearance of our input fields when they are focused or invalid.

- Write the JavaScript logic to validate the form data and display the error messages using methods like `document.getElementById`, `addEventListener`, `event.preventDefault`, `submit`, and `test`.

- Use properties like `value`, `type`, `textContent`, `style.display`, and `length` to access and manipulate the input and error elements.

- Use operators like `===`, `!`, `<`, and `!==` to compare the values and types of the operands.

- Use a regular expression to check the email format using a pattern like `/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/`.

- Use an `if` statement to execute a block of code if the condition is `true`.

- Use a variable named `isValid` to store the validation status and change it to `false` if any of the input fields is invalid.

<br>
## The Grand Finale: A Safer, Happier Form
Open your HTML file in a web browser and try submitting the form. You’ll notice that the form won’t submit unless you fill in the name and provide a valid email. Congratulations, you’ve just transformed your form into a sophisticated conversationalist, gently guiding users to provide accurate information.

> **[CLICK HERE](https://codepen.io/Aniket65/full/dyrXeLP)** to check the **Final Output.**

<br>
## Epilogue: Leveling Up Your Web Skills
Form validation is a very useful and common feature in web development. It can improve the security, accuracy, and usability of our web forms. By using JavaScript, we can perform client-side validation and provide instant feedback to the user. However, we should also perform server-side validation to ensure the data is consistent and reliable.

I hope you enjoyed this article and learned something new. If you did, please give it a like, share it with your friends, and follow me for more articles on web development. Thank you for reading and happy coding! 😊