Native Form Validation: Required, Pattern, and the Constraint Validation API Without JavaScript
Native form validation in HTML5: required, pattern, min, max and length rules, :user-invalid styling, validity states, and when to add JavaScript.
required, type, pattern, min, max, step, minlength and maxlength block submission until the input is valid, with no script at all. Since Chrome 119 shipped :user-invalid in October 2023, every major browser can also style errors only after the user has interacted with a field. The Constraint Validation API is there for the rest: cross-field rules, custom messages and your own error UI. Server-side validation is still required, because none of this stops a determined user.
Most form validation libraries re-implement things the browser already does: checking that a required field is not empty, that an email looks like an email, that a number is within range. Then they add their own error rendering, their own timing rules and their own bugs. Meanwhile the browser’s built-in validation sits unused, often disabled with novalidate because its default error bubbles did not match the design.
Native form validation is the browser’s built-in checking of form controls against constraints declared as HTML attributes. Each control knows whether it is valid, why not, and what message to show. The Constraint Validation API exposes that state to JavaScript through properties such as validity and methods such as checkValidity() and setCustomValidity(). You can use the attributes alone, the attributes plus CSS, or the attributes plus a small amount of script, depending on how much control you need.
Level 1: attributes only
<form action="/signup" method="post">
<label for="email">Work email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" title="Lowercase letters, numbers and underscores">
<label for="seats">Number of seats</label>
<input id="seats" name="seats" type="number" min="1" max="500" step="1" value="5">
<button>Create account</button>
</form>
With no JavaScript, the browser refuses to submit until every field passes, focuses the first invalid one and shows a localized message in the user’s language. For many internal tools, admin panels and simple sites, that is genuinely enough.
| Attribute | Checks | Applies to |
|---|---|---|
required |
Value is not empty; a checkbox is checked; one radio in the group is selected | Most inputs, select, textarea |
type |
Value matches the type’s format, such as email or URL | email, url, number, date types |
pattern |
The whole value matches a regular expression | Text, search, tel, url, email, password |
minlength, maxlength |
Length in characters | Text-like inputs, textarea |
min, max |
Value within range | number, range, date and time types |
step |
Value is a valid step from min |
Same as min and max |
Pattern details that bite
- It is anchored automatically.
pattern="[0-9]{6}"must match the entire value, as if wrapped in^(?:...)$. Do not add your own^and$. - It now uses the
vflag. In 2023, browsers switched to compiling patterns with the newer Unicode sets mode (Chrome 112, Firefox 116, Safari 17). That mode is stricter about some characters inside character classes: a pattern like[\w-]or[a-z0-9_-]with an unescaped hyphen is now invalid. An invalid pattern is ignored silently, apart from a console warning, so the field accepts anything. Escape it:[a-z0-9_\-]. - Empty values pass. Pattern, length and range checks only run when there is a value. Add
requiredif empty should fail too. titleis appended to the error in some browsers, so phrase it as a description of the format.
Level 2: how do you style errors at the right time?
The :invalid pseudo-class matches any field that currently fails its constraints, including empty required fields the moment the page loads. Styling it red makes a fresh form look like it is full of mistakes.
:user-invalid fixes the timing. It only matches after the user has interacted with the field, typically after changing it and moving away, or after trying to submit. Firefox has supported it for years, Safari added it in 16.5, and Chrome 119 completed support in October 2023, so you can now use it everywhere:
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: #b91c1c;
box-shadow: 0 0 0 1px #b91c1c;
}
input:user-invalid + .field-hint {
color: #b91c1c;
}
input:user-valid {
border-color: #15803d;
}
Combined with the attributes, that gives you inline error styling at the right moment with no JavaScript. The browser’s own message bubble still appears on submit.
Level 3: what is the Constraint Validation API?
Every form control has a validity object describing exactly what is wrong:
| Property | True when |
|---|---|
valueMissing |
A required field is empty |
typeMismatch |
The value does not match the type, such as a malformed email |
patternMismatch |
The value does not match pattern |
tooShort, tooLong |
Length outside minlength or maxlength (after user edits) |
rangeUnderflow, rangeOverflow |
Value below min or above max |
stepMismatch |
Value is not a valid step |
badInput |
The browser cannot convert the input, such as letters in a number field |
customError |
A message was set with setCustomValidity() |
valid |
None of the above |
The useful methods:
el.checkValidity()returns true or false and fires aninvalidevent on failure, without showing any UI.el.reportValidity()does the same and shows the browser’s message bubble.el.setCustomValidity("message")marks the field invalid with your message;el.setCustomValidity("")clears it.el.validationMessageholds the browser’s localized message for the current error.
Cross-field rules
Attributes describe one field at a time. Rules that compare fields, such as “confirm password must match” or “end date after start date”, need a few lines of script, and setCustomValidity plugs them into the same native system:
const password = form.elements.password;
const confirm = form.elements.confirm;
function checkMatch() {
confirm.setCustomValidity(
confirm.value && confirm.value !== password.value ? "Passwords do not match" : ""
);
}
password.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);
The most common bug with setCustomValidity is forgetting to clear it. A custom message stays until you set an empty string, so the field remains invalid forever, even after the user fixes it. Always recompute and set the message on every relevant input.
Your own error UI
If the native bubbles do not fit your design, keep the constraints and replace only the presentation. Add novalidate to the form so the browser does not block submission with its bubbles, then use the API yourself:
form.addEventListener("submit", (event) => {
let firstInvalid = null;
for (const field of form.elements) {
if (!field.willValidate) continue;
const error = document.getElementById(`${field.id}-error`);
if (!field.checkValidity()) {
field.setAttribute("aria-invalid", "true");
if (error) { error.textContent = messageFor(field); error.hidden = false; }
firstInvalid ??= field;
} else {
field.removeAttribute("aria-invalid");
if (error) error.hidden = true;
}
}
if (firstInvalid) {
event.preventDefault();
firstInvalid.focus();
}
});
function messageFor(field) {
const v = field.validity;
if (v.valueMissing) return `Enter your ${field.labels[0].textContent.toLowerCase()}`;
if (v.typeMismatch) return "Enter an email address like name@company.com";
if (v.patternMismatch) return field.title;
return field.validationMessage;
}
novalidate turns off only the automatic blocking and bubbles; the constraints, the validity object and :user-invalid all keep working. The error elements are connected to their fields with aria-describedby, as shown in the accessible forms guide.
Skipping validation on purpose
A “Save draft” button should not demand that every required field is filled. Add formnovalidate to that button and the form submits without checks when it is used, while the main submit button still validates.
<button>Publish</button>
<button formnovalidate name="action" value="draft">Save draft</button>
Why does the server still decide?
Client-side validation is a usability feature, not a security control. Anyone can edit the HTML in DevTools, disable JavaScript, or send a request directly with curl. Validate every value again on the server, return field-level errors in a structure the page can display, and treat the browser’s checks as a way to catch mistakes earlier, not as the source of truth.
Frequently Asked Questions
Can I validate a form without JavaScript?
Yes. The required, type, pattern, min, max, step, minlength and maxlength attributes make the browser block submission and show localized error messages until every field is valid. You only need JavaScript for rules that compare fields or for fully custom error presentation.
What is the difference between :invalid and :user-invalid?
:invalid matches any field that currently fails validation, including empty required fields as soon as the page loads. :user-invalid only matches after the user has interacted with the field or tried to submit, which makes it the right choice for error styling. It is supported in all major browsers since Chrome 119.
Why is my pattern attribute not working?
Browsers now compile pattern with the regular expression v flag, which rejects some unescaped characters inside character classes, such as a trailing hyphen in [a-z0-9_-]. An invalid pattern is silently ignored. Escape the character, for example [a-z0-9_\-], and remember that the pattern must match the whole value.
Do I still need server-side validation?
Always. Client-side validation improves usability, but users can bypass it with DevTools, disabled JavaScript or direct requests. The server must validate every value before using it.
Declare the rules, decorate the errors
Start with attributes, because they validate without any script and stay correct when your JavaScript fails to load. Add :user-invalid styles for timely feedback, and reach for the Constraint Validation API only for cross-field rules and custom error UI. You end up with less code than a validation library and behavior that matches what users already know from every other form in their browser. For styling the invalid state without JavaScript classes, the :has() parent selector guide goes further. For the full reference, see the MDN constraint validation guide and the MDN :user-invalid reference. Related reading on this site: HTML5 input types.
Originally posted on 21 November 2023 and post last modified on 21 November 2023