๐Ÿงฐ Web APIs
Estimated reading: 4 minutes 283 views

JavaScript Forms & Validation APIs โ€“ Real-Time Checks Without Reloads


Introduction โ€“ Why Form Validation Matters

From signup pages to checkout flows, HTML forms are the backbone of user interaction on the web. But how do we ensure the input is valid before submitting?

Thatโ€™s where JavaScript Form & Validation APIs shine โ€” enabling real-time feedback, error prevention, and improved user experience without reloading the page.

By the end of this guide, youโ€™ll learn:

How to use the built-in JavaScript Form API
Apply HTML5 validations using attributes
Use checkValidity() and setCustomValidity()
Provide real-time, user-friendly error messages
Ensure performance and accessibility


What Is the JavaScript Forms & Constraint Validation API?

The Forms API and Constraint Validation API are part of the Web APIs that allow JavaScript to:

  • Access and manipulate <form> elements
  • Validate fields in real time using native browser support
  • Prevent submission of invalid forms

These APIs enhance UX while reducing the need for complex manual validation logic.


Accessing Form Elements

Access a form and its inputs via the DOM:

<form id="contactForm">
  <input type="email" name="email" required />
  <button type="submit">Submit</button>
</form>
const form = document.getElementById("contactForm");
const email = form.elements["email"];

Explanation:

  • form.elements["email"] accesses the named input field directly.
  • Forms can be referenced using their id or name.

Basic Validation Using HTML5

HTML5 adds powerful built-in validation through attributes:

AttributeDescription
requiredField must be filled out
type="email"Must be a valid email format
min, maxNumeric limits for input values
patternRegex pattern for custom validation
maxlengthMaximum length for text input

Example:

<input type="text" name="username" required minlength="4" pattern="[A-Za-z0-9]+">

Tip: HTML5 validation prevents submission automatically if fields are invalid.


Using checkValidity() and reportValidity()

checkValidity()

Returns true if all form fields are valid, otherwise false.

if (form.checkValidity()) {
  console.log("Form is valid!");
} else {
  console.log("Form has errors!");
}

reportValidity()

Triggers browser-native tooltips showing validation errors.

form.reportValidity(); // Displays built-in browser error tooltips

Use when you want the browser to display validation messages without submitting.


Custom Validation with setCustomValidity()

You can define your own validation error messages using:

email.setCustomValidity("Please enter a valid corporate email address.");

Set an empty string to clear the message:

email.setCustomValidity(""); // Clears custom message

Use Case: Show custom error for blacklisted domains or special formatting.


Prevent Submission on Invalid Form

JavaScript Form Validation Example

form.addEventListener("submit", function (e) {
  if (!form.checkValidity()) {
    e.preventDefault(); // Block submission
    form.reportValidity(); // Show native errors
  }
});

Explanation:

  • checkValidity() checks if the form is valid.
  • reportValidity() shows validation messages.
  • preventDefault() stops submission if needed.

Real-Time Validation on Input

Provide instant feedback as the user types:

email.addEventListener("input", function () {
  if (email.validity.typeMismatch) {
    email.setCustomValidity("Please use a valid email format.");
  } else {
    email.setCustomValidity("");
  }
});

Use Case: Improve UX by notifying errors early (not just on submit).


Use Cases for Forms & Validation APIs

Use CaseAPI/Method
Prevent empty form submissionrequired, checkValidity()
Validate email formattype="email", validity.typeMismatch
Validate numeric rangemin, max, validity.rangeOverflow
Custom messagessetCustomValidity()
Real-time validationinput or change event listeners

Accessibility & UX Tips

Best Practices:

  • Always use <label> with for attribute for accessibility.
  • Display clear, readable error messages.
  • Group errors using ARIA aria-live for screen reader support.
  • Style invalid fields using :invalid and :valid pseudo-classes.

Validation Properties Summary

Each input element has a validity object with useful properties:

PropertyDescription
validIs field valid overall?
valueMissingRequired value missing?
typeMismatchWrong type (e.g., email)?
patternMismatchDoesn’t match regex pattern?
tooLong/tooShortText length constraint violated?
rangeOverflowValue > max
rangeUnderflowValue < min
stepMismatchNot aligned with step value
customErrorWas setCustomValidity() used?

FAQ โ€“ JavaScript Forms & Validation

Is HTML5 validation enough for security?
No. Always validate on the server as wellโ€”client-side validation can be bypassed.

Whatโ€™s the difference between checkValidity() and reportValidity()?
checkValidity() returns true/false, while reportValidity() displays browser messages.

Can I customize the error tooltip style?
Not directlyโ€”native tooltips can’t be styled. Use JavaScript + CSS to build custom tooltips if needed.

How to show multiple error messages in a form?
Use event listeners on each input, or show a summary list of all invalid fields using form.elements.

Do forms need novalidate?
Use novalidate if you want to disable native HTML5 validation and fully control validation via JavaScript.


Share Now :
Share

Forms & Validation APIs

Or Copy Link

CONTENTS
Scroll to Top