Skip to content
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
Developer Hint

Your Ultimate Guide to Web Development.

Developer Hint

Your Ultimate Guide to Web Development.

  • Home
  • Web Development
  • Tech Explained
  • Developer Tools
  • Contact Us
  • Home
  • Web Development
  • Tech Explained
  • Developer Tools
  • Contact Us
Close

Search

Subscribe
Developer Hint

Your Ultimate Guide to Web Development.

Developer Hint

Your Ultimate Guide to Web Development.

  • Home
  • Web Development
  • Tech Explained
  • Developer Tools
  • Contact Us
  • Home
  • Web Development
  • Tech Explained
  • Developer Tools
  • Contact Us
Close

Search

Subscribe
Home/Web Development/HTML Form Validation Explained
Html Form Validation Explained
Web Development

HTML Form Validation Explained

By Developer Hint
November 30, 2026 5 Min Read
0

Form validation is the checking that happens before a form’s data is accepted, Does the email look like an email? Is the required field filled in? Is the number within range? HTML form validation does a surprising amount of this with nothing but attributes, no JavaScript needed, and it gives visitors quick feedback before anything is sent to your server.

This guide explains the built-in tools, how to customize them with JavaScript, and why you still need to check everything again on the server.

How built-in validation works

When someone submits a form, the browser checks each field against the rules you set, if a field fails, the browser stops the submission, focuses the first problem field, and shows a message.

The form’s submit event does not fire at all while validation is failing, which is worth remembering when you write JavaScript, Fields that pass are left alone, and the form goes through once everything is valid.

<form action="/signup" method="post">
  <label for="email">Email</label>
  <input type="email" id="email" name="email" required>

  <label for="username">Username</label>
  <input type="text" id="username" name="username" required minlength="3" maxlength="20">

  <button type="submit">Create account</button>
</form>

That form validates without a line of JavaScript.

Leave the email empty and the browser complains, type something that is not an email address and it complains again, enter a two-letter username and it points out the minimum length.

The validation attributes

AttributeWorks onWhat it checksBest for
requiredMost inputs, select, textareaThe field is not empty, or a box is checkedMandatory fields and consent checkboxes
minlength and maxlengthText-like inputs and textareaNumber of charactersUsernames, passwords, and short bios
min and maxNumber, range, and date typesThe value falls within a rangeQuantities, ages, and booking dates
stepNumber, range, and date typesThe value matches an allowed incrementWhole numbers or prices in cents
patternText, search, url, tel, email, passwordThe value matches a regular expressionCustom formats such as codes or usernames
typeInputBuilt-in format, such as email or urlFree validation for common data

Type-based checks

Some input types validate on their own. type="email" checks for a basic email shape, and type="url" expects a full address with a scheme, the check is deliberately loose, it accepts anything that looks roughly right, so an address like a@b passes, and it cannot tell you whether the mailbox exists only sending a confirmation email can do that.

The pattern attribute

The pattern attribute takes a regular expression, two details catch people out, the pattern is automatically anchored to the whole value, so you do not add ^ and $ yourself, and you write it without the surrounding slashes.

It also only works on text-based input types, so putting it on type="number" does nothing.

<input
  type="text"
  name="username"
  pattern="[a-zA-Z0-9_]{3,20}"
  title="3 to 20 letters, numbers, or underscores"
  required>

The title attribute is often used to explain the pattern, and some browsers include it in the error message.

Do not rely on that alone, though, since support is inconsistent, put the instructions in visible text near the field.

Turning built-in validation off

Sometimes you want to handle validation entirely yourself, adding novalidate to the form element tells the browser to skip its checks on submit.

A button can also opt out by itself with formnovalidate, which is useful for a “Save draft” button that should work even when required fields are empty.

<form novalidate>
  ...
  <button type="submit">Submit</button>
  <button type="submit" formnovalidate>Save draft</button>
</form>

The Constraint Validation API

The browser exposes its validation system to JavaScript, which lets you read the results and write your own messages, every form field has a few useful members.

The checkValidity() method returns true or false.

The reportValidity() method does the same and also shows the browser’s message.

The validationMessage property holds the text the browser would show. And the validity object tells you exactly what went wrong, with flags such as valueMissing, typeMismatch, patternMismatch, tooShort, rangeUnderflow, and customError.

const email = document.querySelector("#email");

email.addEventListener("input", () => {
  if (email.validity.valueMissing) {
    email.setCustomValidity("Please enter your email address.");
  } else if (email.validity.typeMismatch) {
    email.setCustomValidity("That does not look like an email address.");
  } else {
    email.setCustomValidity("");
  }
});

The setCustomValidity() method is the one to be careful with, passing it a message marks the field invalid and sets that message, passing an empty string clears the error.

If you forget to reset it, the field stays invalid forever, and the form will refuse to submit no matter what the person types.

Checking rules the attributes cannot express

Custom validation shines when a rule depends on more than one field.

A classic example is confirming a password:

const password = document.querySelector("#password");
const confirm = document.querySelector("#confirm");

function checkMatch() {
  confirm.setCustomValidity(
    confirm.value === password.value ? "" : "Passwords do not match."
  );
}

password.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);

Styling valid and invalid fields

CSS gives you the :valid and :invalid pseudo-classes, but they apply from the moment the page loads, so an empty required field is already marked invalid before anyone has touched it.

A page full of red borders on first load is a poor welcome, the :user-invalid and :user-valid pseudo-classes fix this by waiting until the person has interacted with the field, and current browsers support them.

input:user-invalid {
  border-color: #c0392b;
  outline-color: #c0392b;
}

input:user-valid {
  border-color: #2e7d32;
}

Do not rely on color alone to show an error, some people cannot tell red from green, so pair the color with text or an icon.

Making error messages accessible

The browser’s default bubbles are accessible enough in many cases, but they cannot be styled, and they vanish quickly, if you show your own messages, connect them to their fields so assistive technology can announce them, link the message to the input with aria-describedby, and set aria-invalid="true" on the field when it has an error.

Place the message in an element that is announced when it changes, such as one with role="alert" or an aria-live region, keep the wording specific, telling people what to fix and not only that something is wrong. “Enter a date after today” helps far more than “Invalid input”.

<label for="age">Age</label>
<input type="number" id="age" name="age" min="18" max="120" aria-describedby="age-error">
<p id="age-error" role="alert"></p>

Always validate on the server too

Client-side validation is a convenience for honest visitors, it is not a security measure, because anyone can disable it, edit the HTML in developer tools, or send a request directly to your server without using the form at all.

Your server must check every value again, as if the browser had done nothing that includes length limits, formats, and anything that touches a database or a file system, treat browser validation as the friendly first layer and server validation as the real one.

For most forms, start with the attributes and the right input types, they cost almost nothing and work everywhere.

Add setCustomValidity when you want friendlier wording or a rule that spans fields, turn on novalidate and build your own system only when the design needs full control over how and when errors appear, and in that case lean on the Constraint Validation API so you are not reinventing the checks.

And whichever route you take, finish with server-side validation.

Common mistakes to avoid

The most common one is trusting the browser checks and skipping the server, close behind are forgetting to reset setCustomValidity(""), putting pattern on an input type that ignores it, and using :invalid styles that flash red on page load.

Others include relying on placeholders for instructions, writing vague error messages, and making required fields invisible to screen reader users by marking them only with a color.

One more subtle trap is that minlength only triggers after the user has edited the field, so a value filled in by your own script will not be flagged as too short.


Discover more from Developer Hint

Subscribe to get the latest posts sent to your email.

Content Disclosure
This content was created with the assistance of AI tools and thoroughly reviewed, fact-checked, and refined by a human editor to ensure accuracy, clarity, and usefulness for readers.
Advertisements
banner

Tags:

Accessibilityform validationformsHTMLHTML formsJavaScriptweb Basics
Author

Developer Hint

Follow Me
Other Articles
10 Realistic Options For 2026
Previous

Ways to Make Money Online: 10 Realistic Options for 2026

Common Html Form Mistakes Beginners Make
Next

Common HTML Form Mistakes Beginners Make

No Comment! Be the first one.

Leave a Reply Cancel reply

Random Posts

  • Core Web Vitals Explained for Beginners: A Developer’s Guide to Website PerformanceCore Web Vitals Explained for Beginners: A Developer’s Guide to Website Performance
  • 10 Web Development Projects to Build as a Beginner (With What You’ll Actually Learn)10 Web Development Projects to Build as a Beginner (With What You’ll Actually Learn)
  • JavaScript Variable Declarations: Understanding var, let, and constJavaScript Variable Declarations: Understanding var, let, and const
  • What Is Web Development? A Beginner’s Guide for 2026What Is Web Development? A Beginner’s Guide for 2026
  • What Is DNS and How Does It Work? A Beginner’s GuideWhat Is DNS and How Does It Work? A Beginner’s Guide

Popular

Random Posts

  • Responsive Web Design with Bootstrap’s Grid SystemResponsive Web Design with Bootstrap’s Grid System
  • HTML Form Validation ExplainedHTML Form Validation Explained
  • CSS Functions Explained: The Tools That Make Modern CSS PowerfulCSS Functions Explained: The Tools That Make Modern CSS Powerful
  • What Are HTML Attributes?What Are HTML Attributes?
  • CSS Selectors: Class and ID ExplainedCSS Selectors: Class and ID Explained

Legal pages

  • About Us
  • Privacy Policy
  • Terms and Conditions
  • Disclaimer

Trending

Copyright 2026 โ€” Developer Hint. All rights reserved.

Necessary cookies enable essential site features like secure log-ins and consent preference adjustments. They do not store personal data.
None
Functional cookies support features like content sharing on social media, collecting feedback, and enabling third-party tools.
None
Analytical cookies track visitor interactions, providing insights on metrics like visitor count, bounce rate, and traffic sources.
None
Advertisement cookies deliver personalized ads based on your previous visits and analyze the effectiveness of ad campaigns.
None
Unclassified cookies are cookies that we are in the process of classifying, together with the providers of individual cookies.
None