JavaScript is one of the most popular and versatile programming languages that you can get started with today. This programming language is rightfully said to be the language of the web and is essential for adding interactivity to your websites.

The form element is one of the most used HTML elements on websites. These forms take input from the user and process it in the browser or server. However, it's important to validate these inputs to tackle security issues and unwanted bugs.

Understanding DOM Manipulation

Before we proceed to implement client-side form validation with JavaScript, it's essential to understand the Document Object Model, commonly known as the "DOM". The DOM is a standardized API that allows JavaScript to interact with elements on an HTML web page.

Learn More: The Hidden Hero of Websites: Understanding the DOM

For adding event listeners and retrieving user inputs, you'll need to understand the basics of DOM manipulation. Here's an example that explains how you can change the webpage's contents using the DOM API and JavaScript:

        <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p id="paragraph"></p>
  </body>
  <script>
    const paragraph = document.getElementById('parapgraph');
    paragraph.innerText = 'This is a paragraph tag';
  </script>
</html>

In the above code, the <p> tag has an id of paragraph. While writing the JavaScript code, you can access this element by calling the document.getElementById('paragraph') method and manipulating its value.

Now that you've understood the basics of DOM manipulation, let's go ahead and implement form validation.

Form Validation With JavaScript

There are various types of inputs that you can take from a user. Text type, email type, password type, radio buttons, and checkboxes are some of the most common ones that you may encounter. Due to these vast majority of input types, you will need to use different logic to validate each of them.

Before delving into validation, let's take a moment to understand HTML forms and their importance. HTML forms are one of the primary ways you interact with the website as they allow you to enter your data, apply changes, invoke pop-ups, submit information to a server, and more.

The HTML <form> element is used to create these user-facing forms. Here's how you can validate the inputs of an HTML form:

1. Email Validation

Whether you're building an authentication system or just collecting user emails for your newsletter, it's important to validate the email before you can store it in your database or process it. To check if an email satisfies all the required conditions, you can use a regular expression.

HTML:

        <input type="email" placeholder="email@example.io" id="email" required />
    

JavaScript:

        const emailInput = document.getElementById('email');
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (!emailInput.value.match(emailRegex)) {
  alert('Invalid email address.');
}

2. Password Validation

Passwords are a crucial piece of data that needs a special type of validation to ensure its security. Consider a signup form having two fields: password and confirm password fields. To validate these pair of inputs, here are some things you'll need to consider:

  • The password must be more than 6 characters long.
  • The value of the password and the confirm password field must be the same.

HTML:

        <input type="password" placeholder="Enter your password" id="password" required />
<input type="password" placeholder="Enter your password" id="confirm-password" required />

JavaScript:

        const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm-password').value;

if (password.value !== confirmPassword.value) {
  alert('Entered passwords do not match');
}
if (password.length < 6) {
  alert('Password must be more than 6 characters long')
}

3. Radio Input Validation

HTML radio input is a special type of graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options. A common use case of such an input would be for selecting gender. To validate such input, you will need to check if at least one of them is selected.

This can be achieved using the logical operators such as the AND (&&) and NOT (!) operator in this manner:

HTML:

        <label for="male">Male</label>
<input type="radio" id="male" name="gender" value="male" />

<label for="female">Female</label>
<input type="radio" id="female" name="gender" value="female" />

<label for="others">Others</label>
<input type="radio" id="others" name="gender" value="others" />

JavaScript:

        const genders = document.getElementsByName("gender");
const validForm = false;

let i = 0;
while (!validForm && i < radios.length) {
  if (radios[i].checked) validForm = true;
  i++;
}

if (!validForm) alert("Must check some option!");

4. Select Input Validation

The <select> HTML element is used to create a drop-down list. The <option> tags inside the <select> element define the available options in the drop-down list. Each of these <option> tags have a value attribute associated with them.

For the default or initial option, you can set its value to be an empty string so that it'll be deemed as an invalid option. For all the other options, set an appropriate value attribute. Here's an example of how you can validate a <select> input element:

HTML:

        <select id="title" required>
  <option value="">Select One</option>
  <option value="Mr">Mr</option>
  <option value="Mrs">Mrs</option>
  <option value="Ms">Ms</option>
</select>

JavaScript:

        const title = document.getElementById('title');
if (title.value = "") {
  alert('Please select a title');
}

5. Checkbox Validation

Input elements of the type checkbox are rendered by default as boxes that are checked or ticked when activated. A checkbox allows you to select single values for submission in a form. Checkboxes are a popular choice for the "accept terms and conditions" input.

To find out if a checkbox is ticked or not, you can access the checked attribute on the checkbox input. Here's an example:

HTML:

        <input type="checkbox" id="terms">
<label for="terms">I agree to the terms and conditions</label>

JavaScript:

        const terms = document.getElementById('terms');
if (!terms.checked) {
  alert('Please agree to the terms and conditions to proceed further.');
}

Prevention Is Better Than Cure

It's always recommended to validate all the inputs that you receive from a visitor to provide a safe and secure experience. Hackers are always trying to enter malicious data into the input fields to perform cross-site scripting attacks and SQL injections.

Now that you understand how to validate your HTML inputs, why not give it a try by building a form and implementing the strategies you've seen above?