How to Handle Validation Errors When a Form Field Gets Disabled
A checkout form asks for a company name only when the buyer ticks “I am buying for a company”. The buyer ticks the box, presses Continue with the name empty, and gets a red field with “Enter the company name”. Then they change their mind and untick the box, and the form disables the company fields.
What should the red border and the message do now? The field cannot be edited, its value will not be submitted, and nothing the user can do in it will fix it. An error that stays on it is an instruction nobody can follow.
The browser already has an answer to this, and form validation written in JavaScript often gives a different one without anyone having decided so. This guide shows what the browser does, which property to ask, and how to write validation code that takes an error off a field when it is disabled and puts it back when the field is enabled again.
Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.
What the browser does
HTML has a name for a field that takes no part in validation: it is barred
from constraint validation. A disabled field is barred, a field inside a
disabled <fieldset> is barred, and so is a <textarea> or an <input>
with readonly. That holds for every input type: a checkbox or a radio
with readonly can still be changed by the user, yet it is barred all the
same. That is what browsers do, not a technique: readonly is not a valid
attribute on those types and does not make them read-only. A <select> has
no read-only state and ignores the attribute. For a
barred field the browser changes four things at once:
willValidatebecomesfalse;checkValidity()returnstrueand fires noinvalidevent;:invalidand:user-invalidstop matching (so do:validand:user-valid);- the form submits, and the field is not what blocks it.
The two kinds of barring differ in one way that matters for your server. A disabled field is left out of the submitted data. A read-only field is submitted with whatever value it has, unvalidated, so if a read-only value can be wrong, the server has to check it.
So a form that styles its errors only with CSS gets the right behaviour for free:
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: #d6336c;
}
Disable the field and the border goes back to normal. Enable it again and
:user-invalid matches again, with no new input from the user: the browser
remembers that the user has already interacted with the field. I ran this in
Chromium and Firefox with the disabled attribute, with a disabled
fieldset, and with readonly on a text input; all three behave the same
way, and a form reset clears the state. I did not run it in Safari, so
check there before you rely on it.
The fieldset has one exception that is easy to forget. Fields inside the
first <legend> of a disabled fieldset stay enabled. That is how a
checkbox in the legend can switch its own fieldset on and off. Such a field
keeps willValidate === true and keeps its error.
The trap: validity does not follow
CSS alone is rarely enough. An error needs a message, the message has to be
connected to the field for screen readers, and custom components (a
combobox, a date field, a tag input) draw their own border on an element
that is not the field and so does not match :user-invalid itself. So the
script reads the field’s state
and draws the error itself, and the natural thing to read is
field.validity.valid.
That property does not follow the disabled state. This is what a field reports after it is disabled, by its own attribute or by a fieldset, the same in Chromium and Firefox:
| Field and its error | willValidate |
checkValidity() |
validity.valid |
|---|---|---|---|
Required <input> or <textarea>, empty |
false |
true |
true |
Required <select>, empty option chosen |
false |
true |
false |
| Required radio group, nothing checked | false |
true |
false |
| Required checkbox, not checked | false |
true |
false |
type="email" with a malformed address |
false |
true |
false |
pattern that the value does not match |
false |
true |
false |
type="number" below its min |
false |
true |
false |
Error set with setCustomValidity() |
false |
true |
false |
Only the empty required text field turns valid. Every other error stays in
validity while the field is disabled, and a read-only <input> with a
malformed address keeps validity.valid === false in the same way. Code
that draws the error from validity.valid therefore works in the first
manual test, with an empty text input, and leaves a red disabled <select>
in production.
Rule 1: ask willValidate first
The property that carries the browser’s decision is willValidate. One
condition gives a script the behaviour of the pseudo-classes:
function hasErrorToShow(field) {
return field.willValidate && !field.validity.valid
}
Do not rebuild this condition by hand. A check such as
field.disabled || field.closest('fieldset[disabled]') gets the legend
exception wrong, ignores readonly, and has to be kept in step with a
specification that the browser already implements. willValidate covers the
attribute, the fieldset, the legend and readonly in one read.
The same goes for a validator that decides on its own whether the form may
be submitted. Loop over the fields with hasErrorToShow(), or call
form.checkValidity(), which skips barred fields for you. A loop that reads
only validity.valid blocks the form on a field the user cannot reach.
Rule 2: redraw when the field is disabled, not on the next event
Knowing what to ask is half of it. The other half is when. No event tells a
field that it has been disabled (a field that had the focus fires blur,
any other field fires nothing), so validation code that redraws on input,
change and submit keeps the old error on the screen until one of those
happens, and a disabled field produces none of them.
There is a second, quieter version of this problem. Suppose the page
disables the fieldset in a change listener of the checkbox, and the
validation code redraws the whole form on every input event. A click on a
checkbox fires input first and change second, so the redraw runs before
the page has disabled anything. The result is a form that is always one
click behind: the error disappears when the field is enabled again and comes
back when it is disabled.
A MutationObserver removes the dependency on event order. It reports
every change of disabled and readonly, whoever made it:
function watchDisabled(root, callback) {
const observer = new MutationObserver(() => callback())
observer.observe(root, {
attributes: true,
attributeFilter: ['disabled', 'readonly'],
subtree: true
})
return observer
}
Setting field.disabled = true or fieldset.disabled = true from a script
writes the attribute, so the observer sees property changes as well. Two
choices keep it simple and correct:
- Observe the document, not the form. A fieldset that disables the form’s
fields can sit around the form, and a field can belong to the form
through the
form="…"attribute while it sits outside the<form>element. Neither is below the form node. - Redraw every field of the form, not the node that changed. The
callback does not try to work out which fields a change reached. It runs
once for a batch of changes and asks each field for its
willValidateagain, so nested fieldsets and the legend exception need no code. For a form with thousands of fields you would narrow this down; for an ordinary form it is a loop over a few dozen elements.
The observer runs in a microtask after the change, so a test should wait for the drawn state, not read it in the same statement that disables the field.
What it does not see is a field that is moved into or out of a disabled
fieldset, or into its legend, because moving changes no attribute. If your
page does that, add childList: true to the options; the callback redraws
everything, so it needs no other change. That makes the observer run on
every insertion and removal in the document, which is why it is not the
default here.
Rule 3: clear only what the script drew
A field can be invalid for a reason the browser knows nothing about: the server rejected the value and the page rendered it with an error class and a message. That state is not validity. The browser does not remove it when the field is disabled, and validation code should not remove it either, because it has no way to bring it back.
The simplest way to keep the two apart is to give them different hooks. In
this guide the page owns the is-invalid class and the script owns a
data-user-invalid attribute; the stylesheet treats them the same:
.field[data-user-invalid],
.field.is-invalid {
border-color: #d6336c;
}
aria-invalid is shared, so the script owns it and sets it when either
source says the field is invalid; it also runs once at the start, so a
field the server rendered with is-invalid has the attribute before the
user touches anything. The server’s error does not block the submit here:
the page shows it, and the server decides again when the form comes back.
Keeping the server’s error on the screen while the field is disabled is the
page’s decision, not a consequence of this code. Whether an error exists,
whether the field takes part in validation and whether the error is shown
are three separate facts. A page that prefers to hide it can do so in the
stylesheet, with .field.is-invalid:not(:disabled), and keep the class for
the moment the field is enabled.
The message is linked with aria-describedby only while it is shown. By
the accessible description rules a referenced element counts even when it
is hidden, so a permanent link would describe the field with an error it
does not have; I did not listen to this with a screen reader. The field may
carry other descriptions (a hint, the server’s message), so the script adds
and removes its own id without touching the rest:
function toggleToken(field, attribute, token, on) {
const tokens = new Set((field.getAttribute(attribute) ?? '').split(/\s+/).filter(Boolean))
if (on) {
tokens.add(token)
} else {
tokens.delete(token)
}
if (tokens.size > 0) {
field.setAttribute(attribute, [...tokens].join(' '))
} else {
field.removeAttribute(attribute)
}
}
Putting it together
The markup: a checkbox, a fieldset it controls, and one hidden message per
field, named after the field’s id. The form has novalidate, because the
script reports the errors; without it the browser blocks an invalid submit
before the submit event and shows its own bubble.
<form id="checkout" novalidate>
<label>
<input type="checkbox" id="for-company" checked>
I am buying for a company
</label>
<fieldset id="company">
<legend>Company</legend>
<label for="company-name">Company name</label>
<input class="field" id="company-name" name="company" required>
<p id="company-name-error" hidden>Enter the company name.</p>
<label for="company-country">Country</label>
<select class="field" id="company-country" name="country" required>
<option value="">Choose a country</option>
<option>Poland</option>
<option>Germany</option>
</select>
<p id="company-country-error" hidden>Choose a country.</p>
</fieldset>
<button>Continue</button>
</form>
The validation: an error is shown for a field once the user has changed the field or tried to submit the form, and only while the browser validates the field.
function validateForm(form) {
let reported = new WeakSet()
const fields = () => [...form.elements].filter(field => field.matches('input, select, textarea'))
const redraw = field => {
const show = reported.has(field) && hasErrorToShow(field)
const message = document.getElementById(`${field.id}-error`)
field.toggleAttribute('data-user-invalid', show)
if (show || field.classList.contains('is-invalid')) {
field.setAttribute('aria-invalid', 'true')
} else {
field.removeAttribute('aria-invalid')
}
if (message) {
message.hidden = !show
toggleToken(field, 'aria-describedby', message.id, show)
}
}
const redrawAll = () => {
for (const field of fields()) {
redraw(field)
}
}
for (const type of ['input', 'change']) {
form.addEventListener(type, event => {
if (type === 'change') {
reported.add(event.target)
}
redrawAll()
})
}
form.addEventListener('reset', event => {
setTimeout(() => {
if (!event.defaultPrevented) {
reported = new WeakSet()
redrawAll()
}
})
})
form.addEventListener('submit', event => {
for (const field of fields()) {
reported.add(field)
}
redrawAll()
const firstInvalid = fields().find(hasErrorToShow)
if (firstInvalid) {
event.preventDefault()
firstInvalid.focus()
}
})
const observer = watchDisabled(form.ownerDocument, redrawAll)
redrawAll()
return () => observer.disconnect()
}
And the page’s own code, which knows nothing about validation:
const checkout = document.querySelector('#checkout')
validateForm(checkout)
document.querySelector('#for-company').addEventListener('change', event => {
document.querySelector('#company').disabled = !event.target.checked
})
Five details in validateForm() carry the behaviour:
reportedis not touched when a field is disabled. The report is kept, only the drawing stops, so the error returns the moment the field is enabled, as:user-invaliddoes. A form reset is what forgets it, in the next task, so a reset that another listener cancelled forgets nothing.- The function returns a cleanup. The observer watches the document, so it outlives a form that a single-page application removes; call the returned function when the form goes away.
- Every event redraws the whole form. In a required radio group the error belongs to all the radios, so checking one has to clear the others.
- The submit handler finds the first field to focus with
hasErrorToShow(), not withvalidity.valid, so the disabled<select>does not block the form. redraw()removesdata-user-invalidand its own message, and leavesis-invalidand anything else inaria-describedbyalone.
reported is this guide’s reporting policy: an error appears after a change
or a submit attempt. It is close to what :user-invalid does, not a copy of
every rule the browser applies to it.
The listing leaves three things out to stay short. A submit button with
formnovalidate should skip the check (event.submitter.formNoValidate). A
value written by a script fires no event, so call the redraw after it. And a
field attached with form="…" from outside the <form> is redrawn with
the rest, but its change and input events do not pass through the form
element; listen on the document if you use such fields.
If you build a component, not a form script
A component that renders one field should not observe the whole document for it. The platform has a callback for exactly this question. A form-associated custom element is told whenever its disabled state changes because of a fieldset, whether the fieldset was toggled or the element was moved into or out of it:
class DisabledWatch extends HTMLElement {
static formAssociated = true
constructor() {
super()
this.attachInternals()
}
formDisabledCallback(disabled) {
this.dispatchEvent(new CustomEvent('disabledchange', { detail: disabled }))
}
}
if (!customElements.get('disabled-watch')) {
customElements.define('disabled-watch', DisabledWatch)
}
Place a hidden <disabled-watch> next to the field your component owns and
redraw the validation state in its disabledchange listener. The component
does not have to be a custom element itself; the watcher is only a probe
that sits at the same position in the tree. In Chromium and Firefox the
callback ran both when I toggled the fieldset and when I moved the element
into a disabled fieldset and out again; I did not run it in Safari. A
watcher inserted into a fieldset that is already disabled got the callback
at insertion, so add the listener before you insert it, or read
watcher.matches(':disabled') once afterwards.
The watcher answers for fieldsets only. The field’s own disabled and
readonly are attributes the component sets itself, so it already knows
when they change. Two side effects to plan for: the watcher is listed in
form.elements, and it is one more sibling for selectors such as
:last-child.
In React and Vue the usual route is different: disabled is a prop, so the
component renders again when it changes, and the validation state is read
from the field again after that render. The case that needs the watcher
there is the plain <fieldset disabled> around a component, which changes
no prop.
What validation libraries do
There are two models, and which one a library follows decides the answer. If the error is state that the page passes in, the page clears it. If the code computes the error from the field’s validity, it should follow the browser, because the browser is what the native fields next to it follow.
The three component libraries I read keep the error on a disabled field. I
read the published packages and did not run them. In React Aria the
validation state in useFormValidationState.ts (react-stately 3.51.0)
does not read isDisabled, and useTextField.ts (react-aria 3.53.1) sets
aria-invalid next to disabled. In the Zag.js 1.49.0 combobox invalid
comes from props and is rendered next to disabled
(combobox.connect.mjs). MUI 9.6.0 takes error from a prop; a disabled
outlined input gets a grey border (OutlinedInput.mjs), while
aria-invalid stays (InputBase.mjs). I found no stated reason for keeping
the error in any of the three. In all of them an error can be a prop the
page controls, so the page can clear it, but it has to remember to.
Form validators for plain JavaScript mark fields with a class, like the code in this guide. I ran four of them with their default options in Chromium and Firefox, with a required empty text field that the page disables after a failed submit:
| Library | When the field is disabled | Next submit with the field disabled |
|---|---|---|
| jQuery Validation 1.22.1 | class and message stay | submits; the message goes, the class and aria-invalid stay |
| Parsley 2.9.2 | mark stays | blocked: the disabled field is validated |
| Pristine 1.1.0 | mark stays | blocked: the disabled field is validated |
| Just-validate 4.3.0 | mark stays | blocked: the disabled field is validated |
None of the four reacts at the moment the field is disabled, and with the
defaults three of them stop the form on a field the user cannot edit.
Parsley skips disabled fields when :disabled is added to its excluded
option; I did not look for an equivalent in Pristine and Just-validate.
The one library I found that behaves like the browser in both directions is
Angular’s reactive forms (@angular/forms 22.3.0, fesm2022/forms.mjs,
read and not run): disable() on a control sets its status to disabled and
its errors to null, and enable() validates it again. It can do that
because the control, not the DOM, owns the disabled state.
Common mistakes
- Reading
validity.validwithoutwillValidate. It passes with an empty text input and fails with a select, a radio group, a checkbox, an address or a pattern. - Checking
disabledby hand.closest('fieldset[disabled]')is wrong for a field in the first legend and says nothing aboutreadonly. - Redrawing only on
input,changeandsubmit. A field that is disabled by a button, by a script, or in achangelistener that runs after yours keeps its old error. - Redrawing only the field that changed. The other radios of a required group keep their error after one of them is checked.
- Forgetting the report. If disabling a field also forgets that it was reported, the error does not return when the field is enabled and the user submits an incomplete form a second time to see it.
- Leaving the computed
aria-invalidand the message link. A read-only field can still take focus, so anaria-invalidleft on it may be read out for a value the user cannot change. I did not measure this with a screen reader; listen to your form with the ones your users have. - Hiding a section without disabling it. A required field in a hidden
part of the form still validates, so the submit is blocked by an error
nobody sees and
focus()on it does nothing. Disable the fieldset you hide. - Clearing the server’s error. It was not computed from validity, so enabling the field cannot restore it.
How to test it
The pseudo-classes and the barred state are the browser’s work, so run
these in a real browser. In a quick check jsdom answered willValidate and
:invalid correctly for a field in a disabled fieldset, but did not match
:user-invalid, so do not take a green unit test as the answer. “Error” below means all four things the script draws: the
data-user-invalid hook, aria-invalid="true", the visible message and its
id in aria-describedby. Wait for that state after each step; the observer
runs after the change, not inside it.
- required text input, select and radio group: click the submit button, see three errors, disable each one with the attribute, see none;
- the same through a disabled fieldset, and through a fieldset around the form;
readonlyon an email input with a malformed address (an empty required input turns valid by itself and would pass with the wrong code);- enable again: the errors return without another submit;
- submit while the fields are disabled: the
submitevent is not cancelled; - check one radio of the group: every radio loses its error;
- reset the form: no errors, and none after disabling and enabling; a reset that a listener cancels keeps them;
- call the cleanup: disabling a field no longer redraws anything;
- a field in the fieldset’s first legend keeps its error while the fieldset is disabled;
- a field rendered with the server’s error class has
aria-invalidfrom the start and keeps both through disabling and enabling; - a real click on the checkbox that disables the fieldset in its own
changelistener: the errors follow each click, not the one before it; - disable and enable from a button outside the form;
- if you use the watcher element: toggle its fieldset, then move it into a disabled fieldset and out.
Run them in every browser you support. Everything in this guide was measured in Chromium and Firefox only.
In CoreUI
In CoreUI v6 the form components for vanilla JavaScript, React and Vue that
compute their state from the browser’s validation read willValidate
before validity, so a disabled or read-only component shows no reported
error and shows it again once it takes part in validation. The vanilla
components that sit in a fieldset use the form-associated watcher shown
above to redraw when the fieldset changes. A state that the page gives a
component stays until the page takes it away.



