Web forms often need to reject incomplete or inconsistent input before an application uses it. The Constraint Validation API lets JavaScript validate those forms with the browser's built-in rules and custom messages.

Native constraints handle missing values, email syntax, and minimum lengths. A password confirmation needs a rule that compares two fields, so setCustomValidity() adds an error that remains active until it is cleared with an empty string.

A successful check means the fields pass the browser's rules, not that an account exists or an email address belongs to its user. Client-side validation can be bypassed, so a real signup endpoint must validate the data on the server too.

Steps to validate forms with the Constraint Validation API:

  1. Create a file named index.html in a new folder using your text editor.
    index.html
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Signup validation</title>
      <link rel="stylesheet" href="styles.css">
      <script src="signup-validation.js" defer></script>
    </head>
    <body>
    </body>
    </html>

    The stylesheet and script will be in the same folder. defer lets the browser parse the form before the script selects its controls.
    Related: Load JavaScript with defer

  2. Insert the signup form immediately before </body> in index.html.
    index.html
      <form id="signup-form" aria-labelledby="signup-heading">
        <h1 id="signup-heading">Create account</h1>
        <label for="signup-email">Email address</label>
        <input id="signup-email" name="email" type="email" autocomplete="email" required>
        <label for="signup-password">Password (at least 8 characters)</label>
        <input id="signup-password" name="password" type="password" autocomplete="new-password" minlength="8" required>
        <label for="confirm-password">Confirm password</label>
        <input id="confirm-password" name="confirm_password" type="password" autocomplete="new-password" required>
        <button id="validate-signup" type="button">Validate signup</button>
        <p id="form-status" role="status">Form has not been checked yet.</p>
      </form>

    required rejects empty fields, type=“email” checks email syntax, and minlength=“8” rejects a password shorter than eight characters when the user types it. The button has type=“button” because it checks the form without submitting it.

  3. Create styles.css in the same folder with styles for checked fields.
    styles.css
    body {
      margin: 24px;
      font: 16px/1.4 system-ui, sans-serif;
      color: #172033;
    }
    #signup-form {
      display: grid;
      gap: 10px;
      max-width: 420px;
    }
    h1, #form-status { margin: 0; }
    label { font-weight: 600; }
    input, button {
      box-sizing: border-box;
      padding: 10px;
      font: inherit;
      border: 2px solid #b9c5d6;
      border-radius: 6px;
    }
    button { background: #155fa8; color: white; }
    .was-validated input:invalid {
      border-color: #b42318;
      background: #fff4f2;
    }
    .was-validated input:valid { border-color: #1a7f37; }

    The was-validated class delays red and green borders until the first validation attempt. The status text identifies the error without relying on color alone.

  4. Create signup-validation.js in the same folder with the password comparison rule.
    signup-validation.js
    const form = document.querySelector("#signup-form");
    const password = document.querySelector("#signup-password");
    const confirmPassword = document.querySelector("#confirm-password");
    const validateButton = document.querySelector("#validate-signup");
    const status = document.querySelector("#form-status");
     
    function validatePasswordMatch() {
      const hasConfirmation = confirmPassword.value.length > 0;
      const passwordsMatch = password.value === confirmPassword.value;
     
      confirmPassword.setCustomValidity(
        hasConfirmation && !passwordsMatch ? "Passwords must match." : "",
      );
    }

    An empty confirmation uses its native required message. A nonempty mismatch gets the custom message; passing “” clears that custom error after correction.
    Related: Select DOM elements with JavaScript

  5. Append the event handlers to the end of signup-validation.js.
    signup-validation.js
    form.addEventListener("input", () => {
      validatePasswordMatch();
      status.textContent = "Form has not been checked yet.";
    });
     
    validateButton.addEventListener("click", () => {
      validatePasswordMatch();
      form.classList.add("was-validated");
     
      if (!form.reportValidity()) {
        status.textContent = form.querySelector(":invalid").validationMessage;
        return;
      }
     
      const formData = new FormData(form);
      status.textContent = `Ready to create account for ${formData.get("email")}.`;
    });

    reportValidity() returns false for an invalid form and displays the browser's validation feedback. The early return prevents the readiness path from running. checkValidity() also returns a validity result, but does not display the browser's feedback. The input handler rechecks the comparison when either password changes and removes any stale readiness message.

    Browser checks do not protect a signup endpoint from direct requests or altered page code. Server-side validation is still required before accepting data.

    A real submit flow can use a submit listener. form.submit() bypasses constraint validation, whereas requestSubmit() follows the normal validation path.
    Related: Handle form submission with JavaScript

  6. Save index.html, styles.css, and signup-validation.js in the same folder.
  7. Open index.html in your browser.
  8. Fill the form with email user@example.com, password example-password, and confirmation different-password.

    These are demonstration values; the password fields mask what you type.

  9. Click Validate signup.
  10. Replace the Confirm password value with example-password.

    The failed attempt shows Passwords must match. and an invalid confirmation field. Matching values clear the custom error, and the status returns to Form has not been checked yet. until another validation attempt.

  11. Click Validate signup again.
  12. Confirm that the status reads Ready to create account for user@example.com.

    All three fields now pass validation. No account has been created and no request has been sent.

Share this guide