Skip to content

JavaScript Tutorial Forms and Validation

Client-Side Form Validation in JavaScript

Lesson 124 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Before writing any validation code, use what the browser already provides.

Built-in validation attributes

index.html
HTML
<input type="email" required>
<input type="text" minlength="3" maxlength="20" pattern="[a-z0-9_]+" title="Lowercase letters, digits and underscores">
<input type="number" min="1" max="10" step="1">
<input type="url">
AttributeChecks
requirednot empty
type="email", url, number…the right format
minlength, maxlengthtext length
min, max, stepnumber or date range
patterna regular expression (the whole value must match)

When a form is submitted, the browser checks all of them, blocks the submission and shows its own messages.

The Constraint Validation API

JavaScript can ask about the state of a field.

index.html
HTML
<input id="email" type="email" required value="not-an-email">
<script>
  const input = document.querySelector("#email");

  console.log(input.checkValidity());          // → false
  console.log(input.validity.typeMismatch);    // → true
  console.log(input.validity.valueMissing);    // → false
  console.log(input.validationMessage.length > 0); // → true (the browser's own message)
</script>
validity flagMeaning
valueMissingrequired but empty
typeMismatchwrong format for the type
tooShort, tooLonglength rules
rangeUnderflow, rangeOverflowoutside min / max
patternMismatchfailed pattern
customErrorset with setCustomValidity
valideverything is fine

Custom messages: setCustomValidity

index.html
HTML
<form id="f">
  <input id="pw" type="password" minlength="8" placeholder="Password" required>
  <button>Save</button>
</form>
<script>
  const pw = document.querySelector("#pw");

  pw.addEventListener("input", () => {
    if (pw.validity.tooShort) {
      pw.setCustomValidity("Please use at least 8 characters.");
    } else {
      pw.setCustomValidity("");          // an empty string means "valid"
    }
  });
</script>

Remember to clear the custom message with "", or the field stays invalid forever.

Checking the whole form

script.js
JS
if (!form.checkValidity()) {
  form.reportValidity();    // shows the browser's messages
}

Styling states in CSS

:valid, :invalid and :user-invalid let CSS style fields. See Form Validation Styles in the CSS course.

Turning the browser UI off

Add novalidate to the form if you want to show your own messages for every rule. The next lesson shows how: Custom Error Messages.

dangerous
Never trust the client
All of this runs in the user’s browser, where it can be edited or bypassed. It is for a good experience. The server must validate again.