JavaScript Answers

How to require two form fields to match with HTML5 with JavaScript?

Spread the love

To require two form fields to match in HTML5 with JavaScript, you can use the pattern attribute along with a regular expression to validate both fields.

For example we write:

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Matching Form Fields with HTML5 and JavaScript</title>

  <form id="myForm">
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>

    <label for="confirmPassword">Confirm Password:</label>
    <input type="password" id="confirmPassword" name="confirmPassword" required>

    <input type="submit" value="Submit">

    document.getElementById("myForm").addEventListener("submit", function(event) {
      var password = document.getElementById("password").value;
      var confirmPassword = document.getElementById("confirmPassword").value;

      if (password !== confirmPassword) {
        alert("Passwords do not match!");
        event.preventDefault(); // Prevent form submission


In this example, the JavaScript code adds an event listener to the form’s submit event. When the form is submitted, it retrieves the values of the password and confirm password fields.

If the two values do not match, an alert is displayed, and event.preventDefault() is called to prevent the form from being submitted.

Additionally, you can use the pattern attribute along with a regular expression directly in the HTML to enforce a specific pattern for the fields.

For example, if you want to require that the password contains at least one uppercase letter, one lowercase letter, and one digit, you can use a pattern like this:

<input type="password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required>

This pattern requires the password to be at least 8 characters long and contain at least one digit, one lowercase letter, and one uppercase letter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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