Build an input
Build a web component input with a label, hint, and character count, your own validation messages, Enter that submits like a native box, and styled states.
- 01Build a field in one shadow rootKeep a real input with its label, hint, count, and error beside it, so the box gets one name and a full description.
- 02Write and show your own messagesCheck a length limit that
maxlengthcan't, word each error yourself, show it after a failed send, and announce the count after a pause. - 03Match a native box on Enter and in every statePress the form's first submit button on Enter, and style hover, focus, filled, too long, error, disabled, and readonly in light, dark, and forced colors.
How do you build a text input web component?
It's a busy week at Leaf and Kettle. Meena adds a gift message to the order form, so people can send tea with a note. Ravi writes each note by hand on a small card. A card holds 140 characters, so Meena gives the box maxlength="140".
Asha pastes the message she wrote for Ravi's birthday and presses Send. The card comes back without her name. Nothing told her the message was too long. How do you build a text field that tells her, and still works like a normal input?
A text input web component is a form-associated custom element that wraps a real input. Its shadow root holds the label, a hint, a count, and an error next to the box. It checks its own rules and shows its own messages. Enter asks the form to send, as in a native box, and custom states give every state a look.
Here is Meena's first box. Try what Asha did:
<form> <label>Gift message <input name="message" maxlength="140"></label> <button>Send</button></form><p>Asha's message: <q>Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha</q></p><button id="fill">Fill from last order</button><script> const form = document.querySelector("form"); const box = form.elements.message; document.querySelector("#fill").addEventListener("click", () => { box.value = document.querySelector("q").textContent; }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log(`Sent ${box.value.length} characters, last word "${box.value.split(" ").at(-1)}"`); });</script>- Line 2 is the box, with
maxlength="140". Line 3 is Send. - Line 5 is Asha's message. Select it, copy it, and paste it into the box.
- Line 6 is a Fill from last order button. When it's clicked, lines 10 to 12 put her message in the box from a script.
- Lines 13 to 16 stop the real send. Line 15 prints how many characters the form would send, and the last word.
Paste the message and press Send: Sent 140 characters, last word "oolong.". The box cut off the last 11 characters, " Love, Asha". Now press Fill from last order, then Send: Sent 151 characters, last word "Asha". Nothing was cut this time, and the form sent it anyway.
So maxlength failed Asha twice. It cut her paste without a word. And it let a script's text through. This lesson builds tea-field, a field that tells her instead.
At the post office, a paper form has a box for each answer. The question is printed above the box. Small print under it says what to write. A row of little squares shows how much room is left. If something is wrong, the clerk writes a note beside the box.
- In real life: The question above the box
- In JavaScript: The label, which names the input
- In real life: The small print under it
- In JavaScript: The hint
- In real life: The row of little squares
- In JavaScript: The character count
- In real life: The clerk's note beside the box
- In JavaScript: The error message
Build the whole field, not just the box. Keep a real input, and put its label, hint, count, and error beside it in one shadow root. Check your own rules in your own words. Make Enter act as it does in a native box, and give every state a look.
tea-field is a form-associated custom element, from lesson 16.1. It keeps a real input in its shadow root, as lesson 16.5's search box did. Form-associated elements work in Chrome 77, Firefox 98, and Safari 16.4 and later.
How do you label and describe a web component input?
Start with the parts. A field is more than a box. It has five parts, and the first tea-field.js keeps all five in its shadow root:
const characters = (count) => (count === 1 ? "1 character" : `${count} characters`);
const template = document.createElement("template");
template.innerHTML = `
<style>label, input, small { display: block; }</style>
<label part="label" for="box"><slot name="label"></slot></label>
<input part="input" id="box" aria-describedby="hint count error">
<small part="hint" id="hint"><slot name="hint"></slot></small>
<small part="count" id="count"></small>
<small part="error" id="error"></small>`;
class TeaField extends HTMLElement {
static formAssociated = true;
#internals = this.attachInternals();
#box;
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.append(template.content.cloneNode(true));
if ("referenceTarget" in ShadowRoot.prototype) this.shadowRoot.referenceTarget = "box";
this.#box = this.shadowRoot.getElementById("box");
this.#box.addEventListener("input", () => this.#update());
this.#update();
}
#update() {
const max = Number(this.getAttribute("maxlength"));
this.#internals.setFormValue(this.#box.value);
this.shadowRoot.getElementById("count").textContent = `${characters(max - this.#box.value.length)} left`;
}
}
customElements.define("tea-field", TeaField);- Line 1 turns a number into words, like 1 character or 140 characters.
- Lines 5 to 9 are the five parts. Each has a part name, so a page can style it with
::part()(lesson 12.2). - Line 5 is the label. Its words come from the label slot, and
for="box"points it at the box. - Line 6 is the box, a real input. Its
aria-describedbylists three ids: the hint, the count, and the error. - Line 7 is the hint, from the hint slot. Lines 8 and 9 are the count and the error, which the class fills in.
- Line 12 makes it form-associated, and line 13 gets its internals. Line 18 delegates focus, so a click on the label or the tag lands in the box (MDN).
- Line 20 turns on Reference Target where the browser has it, as the search box did. Lines 26 to 30 hand the form the text, as in lesson 16.2, and write the count.
Here is the field on a page, with words in both slots:
<form> <tea-field name="message" maxlength="140"> <span slot="label">Gift message</span> <span slot="hint">We write it on the card by hand.</span> </tea-field> <button>Send</button></form><p>Asha's message: <q>Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha</q></p><script src="tea-field.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); const text = new FormData(form).get("message"); console.log(`Sent ${text.length} characters, last word "${text.split(" ").at(-1)}"`); });</script>- Lines 2 to 5 are the field. Line 3 fills the label slot, and line 4 fills the hint slot.
- Lines 12 to 16 print what the form would send.
This is Chrome's accessibility tree for the box:
textbox "Gift message", description: "We write it on the card by hand. 140 characters left"One row. The box is named Gift message, by the label slot's words. Its description is the hint, then the count. The tag itself gets no name. Why does it all connect? An id only reaches its own tree, as lesson 13.4 showed. Here every id lives in one shadow root.
Paste Asha's message into this field. Nothing is cut now. But the count says -11 characters left, and Send prints Sent 151 characters, last word "Asha". Nothing stops it yet. The next section adds the rule.
What if the page has its own label?
Many pages label an input with <label for>. That should work on tea-field too. But tea-field already has a label of its own. Try four pages. Only lines 2 and 4 change:
<form> <!-- no label on the page --> <tea-field id="gift" name="message" maxlength="140"> <span slot="label">Gift message</span> </tea-field></form><script src="tea-field.js"></script>textbox "Gift message", description: "140 characters left"The slot's words sit inside the field's own label, which points at the box with for="box". The box is named Gift message, and nothing else is.
- The label slot:
textbox "Gift message". - A page label:
textbox "Gift message". Reference Target passes the page label on to the box (lesson 16.5). - Both:
textbox "Gift message Gift message". Chrome joins the two labels. - Both, with the fix:
textbox "Gift message"again.
With both, a screen reader says the name twice, like two name cards for one guest. The fix is in the last choice's tab:
connectedCallback() {
const own = this.shadowRoot.querySelector("label");
if (!own) return;
const page = [...this.#internals.labels, ...this.#box.labels].filter((label) => label !== own);
if (page.length === 0) return;
own.remove();
if (!("referenceTarget" in ShadowRoot.prototype)) this.#box.ariaLabelledByElements = page;
}- Line 2 finds the field's own label.
- Line 4 collects every other label.
internals.labelslists the page's labels for the tag (MDN). With Reference Target, Chrome lists them on the box instead, inbox.labels. So line 4 looks in both, and leaves out the field's own. - Line 6 takes the field's own label out when the page has one.
- Line 7 is for browsers without Reference Target. There the box points at the page's labels with
ariaLabelledByElements, as in lesson 13.3.
Click the page label in any choice, and focus lands in the box. Write the page label before the field, so it exists when the field joins the page.
Reference Target is on by default only in Chrome 152 and later (Chrome's release notes). Firefox 144 and Safari 26 have it behind a setting.
Why it matters: a field with one shadow root needs no tricks to tie its label, hint, and error to the box. Only a second label needs care.
How do you show validation messages in a web component input?
Why maxlength isn't enough
Go back to the first box. The HTML Standard gives maxlength two rules:
- A browser may stop a person from typing or pasting past the limit. Chrome does: it cut Asha's paste at 140.
- The box is too long only if a person's edit left it too long. Then
validity.tooLongis true (MDN). Text from a script never counts.
So Fill from last order slipped 151 characters past it, and the form sent them all. The GOV.UK Design System's character count takes another way. It lets people type or paste past the limit, then tells them how many characters are too many. They can paste their whole answer, then edit it down. tea-field does the same, so it never passes maxlength on to its box.
Ravi used to write each note until the card was full, then stop, even in the middle of a word. Now Meena reads the message back first. "That's 11 letters too long. Which words should go?" The customer picks, and the card comes out right.
- In real life: Ravi stopping at the edge of the card
- In JavaScript: maxlength cutting the paste
- In real life: Meena counting the letters first
- In JavaScript: tea-field's count
- In real life: "That's 11 letters too long"
- In JavaScript: 11 characters too many
- In real life: The customer picks what to cut
- In JavaScript: Asha edits her message down
Writing your own messages
Here are tea-field's rules, in the new tea-field.js:
#update() {
const text = this.#box.value;
const max = Number(this.getAttribute("maxlength"));
const over = text.length - max;
this.#internals.setFormValue(text);
const count = this.shadowRoot.getElementById("count");
count.textContent = over > 0 ? `${characters(over)} too many` : `${characters(-over)} left`;
if (this.hasAttribute("required") && text === "") {
this.#internals.setValidity({ valueMissing: true }, "Enter a message for the card.", this.#box);
} else if (over > 0) {
this.#internals.setValidity({ tooLong: true }, `Gift message must be ${max} characters or less.`, this.#box);
} else {
this.#internals.setValidity({});
}
const shown = this.#tried && !this.#internals.validity.valid;
this.shadowRoot.getElementById("error").textContent = shown ? this.#internals.validationMessage : "";
this.#box.ariaInvalid = shown ? "true" : null;
}
#announce() {
clearTimeout(this.#pause);
this.#pause = setTimeout(() => this.#box.ariaNotify?.(this.shadowRoot.getElementById("count").textContent), 1000);
}- Line 4 works out how far over the limit the text is. Line 7 writes the count: so many too many, or so many left.
- Lines 8 and 9: a required, empty box sets
valueMissing, with the words Enter a message for the card. - Lines 10 and 11: a box over the limit sets
tooLong, with Gift message must be 140 characters or less. - Both pass the box as the anchor (MDN), so Chrome's bubble points at it. Line 13 clears the flags.
- Line 15 decides whether the error shows. Lines 16 and 17 show it and mark the box invalid, as in lesson 16.3.
Why these words? The GOV.UK guide to error messages says to describe what happened and how to fix it. Different errors need different messages. It suggests an instruction for an empty field, like Enter your name. For text that's too long, it suggests a description, like Name must be 35 characters or less. It also says not to write please, and to avoid general words like This field is required.
Here is the field with its rules. Try each step:
<form> <tea-field name="message" maxlength="140" required> <span slot="label">Gift message</span> <span slot="hint">We write it on the card by hand.</span> </tea-field> <button>Send</button></form><p>Asha's message: <q>Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha</q></p><button id="fill">Fill from last order</button><script src="tea-field.js"></script><script> const form = document.querySelector("form"); const field = form.elements.message; document.querySelector("#fill").addEventListener("click", () => { field.value = document.querySelector("q").textContent; }); form.addEventListener("submit", (event) => { event.preventDefault(); console.log(`Sent ${field.value.length} characters, last word "${field.value.split(" ").at(-1)}"`); });</script>- Line 2 makes the field required, with a limit of 140.
- Lines 14 to 16 put Asha's message in the field from a script, through its new value setter.
- Press Send with the box empty. Chrome's bubble says Enter a message for the card. at the box, and focus moves there. The same words show under the box.
- Paste Asha's message. The count says
11 characters too many, and the error changes to Gift message must be 140 characters or less. - Press Fill from last order, then Send. Nothing is sent. A script's text is checked too.
- Take out the sentence Thank you for every cup of jasmine tea this year. Press Send:
Sent 101 characters, last word "Asha".
Here are the box's rows in Chrome's tree after steps 1 and 2:
textbox "Gift message", focused, invalid, description: "We write it on the card by hand. 140 characters left Enter a message for the card."
textbox "Gift message", focused, invalid, description: "We write it on the card by hand. 11 characters too many Gift message must be 140 characters or less."Everything sits on the box, which has focus. A screen reader hears the name, that it's invalid, and the description: the hint, the count, and the error.
When should the error show?
Line 15 shows the error only after the form has tried to send. The invalid event marks that moment. Lesson 16.3 explains why it doesn't show sooner, as you leave the box. The error would appear as you reach for Send, push the button down, and the click would miss. Once it shows, it changes with every key, and it goes as soon as the text is right.
Chrome's bubble and your own message
When a send fails, two messages show. Chrome's bubble appears at the anchor, and Chrome takes it away as soon as focus moves on. Your own message stays under the box until the text is fixed. Both use the same words, because the bubble shows the field's message. Can you hide the bubble? Try both:
<form> <tea-field name="message" maxlength="140"> <span slot="label">Gift message</span> </tea-field> <button>Send</button></form><script src="tea-field.js"></script><script> const field = document.querySelector("tea-field"); field.value = "Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha"; // Line 11 leaves the invalid event alone. document.querySelector("button").addEventListener("click", () => { setTimeout(() => console.log("Focus is on", document.activeElement.localName)); });</script>The form fires invalid at the field, and nothing cancels it. So Chrome shows its bubble with the field's own words, and moves focus into the box: Focus is on tea-field.
- Keep the bubble:
Focus is on tea-field. - Hide the bubble:
Focus is on button.
Cancelling invalid hides the bubble. It also stops Chrome from moving focus. The HTML Standard reports only the controls whose invalid event wasn't cancelled, and moving focus is part of that report. For a form-associated element, it uses the validation anchor. So if you hide the bubble, move focus to the first invalid field yourself. tea-field keeps it.
Meena spots a mistake on Asha's form and calls across the room: "Your message is too long!" Asha turns to look, and Meena points at the box. Once Asha looks away, the call is gone. So Meena also clips a note to the box, and it stays until Asha fixes it.
- In real life: Meena's call across the room
- In JavaScript: Chrome's bubble
- In real life: Asha turning to look
- In JavaScript: Focus moving to the box
- In real life: The call is gone once she looks away
- In JavaScript: The bubble goes when focus moves on
- In real life: The note clipped to the box
- In JavaScript: The field's own error
- In real life: It stays until she fixes it
- In JavaScript: The error shows until the text is right
Announcing the count
The count changes with every key. If it were a live region, a screen reader would read it after every key. The GOV.UK count waits instead. People who see the screen get the count as they type. Screen reader users hear it when they stop typing.
tea-field does the same with ariaNotify() from lesson 13.5. Lines 20 to 23 of the rules wait for one second with no typing, then say the count, politely (MDN). Here the page also prints what the field says:
<form> <tea-field name="message" maxlength="140"> <span slot="label">Gift message</span> </tea-field></form><script> const say = Element.prototype.ariaNotify; Element.prototype.ariaNotify = function (message) { console.log("ariaNotify:", message); return say?.call(this, message); };</script><script src="tea-field.js"></script>Lines 7 to 11 wrap ariaNotify(), so each call also prints its words. Line 10 still calls the real one.
Type Happy birthday quickly, then stop. A second later it prints ariaNotify: 126 characters left. Type again, and the next line comes only when you stop. The count is also in the box's description, so a screen reader reads it when focus lands on the box.
Why it matters: a message only helps if it says what to do, shows at the right moment, and reaches everyone.
How does Enter submit a form from a web component input?
The box in tea-field's shadow root has no form, so Enter alone does nothing. Lesson 16.5's search box fixed that with requestSubmit(). But that isn't what Enter does in a native box. Lesson 17.2 showed the HTML Standard's rules. Enter clicks the form's first submit button. With none, the form sends itself only if it has one text field. requestSubmit() skips both questions (MDN).
Here is tea-field's Enter. First, the listener in the constructor:
this.#box.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
setTimeout(() => {
if (!event.defaultPrevented) this.#enter();
});
});Lines 1 to 5 follow the search box's. Line 2 skips other keys, and Enter while an input method is still picking a word. Line 3 waits a task, so a listener on the page can cancel the key. Line 4 now calls #enter():
#enter() {
const form = this.#internals.form;
if (!form) return;
const fields = [...form.elements];
const button = fields.find((field) => field.type === "submit");
if (button) {
if (!button.matches(":disabled")) button.click();
return;
}
const texts = fields.filter((field) => field.localName === "tea-field" || (field.localName === "input" && textTypes.includes(field.type)));
if (texts.length === 1) form.requestSubmit();
}- Line 4 takes the form's controls, in order.
- Line 5 finds the first one whose type is submit: the default button. A native button with no type counts. So does the kit's tea-button, whose type is submit too.
- Line 7 clicks it, unless it's disabled. Line 8 stops either way.
- Line 10 counts the text fields: tea-fields, and inputs of the types the standard counts. Line 11 sends only when there's one.
Web Awesome's submitForm() asks the same two questions. Try four forms. Each page has a native input's form and tea-field's form, with the same line 3 and line 7. Type Hi in each box and press Enter:
<form id="native"> <label>Native input <input name="message"></label> <button name="wrap" value="paper">Send</button></form><form id="custom"> <tea-field name="message" maxlength="140"><span slot="label">tea-field</span></tea-field> <button name="wrap" value="paper">Send</button></form><script type="module" src="tea-kit/index.js"></script><script src="tea-field.js"></script><script> for (const form of document.forms) { form.addEventListener("submit", (event) => { event.preventDefault(); const sent = new URLSearchParams(new FormData(form, event.submitter)); console.log(`${form.id}: Sent ${sent} by ${event.submitter?.localName ?? "the form"}`); }); }</script>Send is each form's first submit button. Enter clicks it in both forms, so its name and value are sent, and it's the submitter.
- A Send button:
native: Sent message=Hi&wrap=paper by button, and the same line for custom. - A disabled Send button: nothing from either form.
- Two text fields: nothing from either form.
- Only the kit's button:
native: Sent message=Hi by the form, butcustom: Sent message=Hi&wrap=paper by the form.
Read each row across: what the form has, then what Enter does in each kind of box.
| What the form has | Enter in a native input | requestSubmit() on every Enter | tea-field's rule |
|---|---|---|---|
| A Send button with a name and a value. | It clicks Send, so Send's name and value are sent. | It sends without Send's name and value. | It clicks Send, so Send's name and value are sent. |
| A disabled Send button. | It does nothing. | It sends anyway. | It does nothing. |
| Two text fields and no button. | It does nothing. | It sends anyway. | It does nothing. |
| Only a tea-button. | The form sends itself, without the button's value. | The form sends itself, without the button's value. | It clicks tea-button, which sends its value. |
The last row is the one place tea-field goes past a native box. The browser doesn't count tea-button as a submit button. tea-field finds it by its type, so Enter presses the kit's button, which lends its value. Think of Asha saying "That's all" at the counter in lesson 17.2: tea-field also reads the sticker that says Order.
The browser can't count your field either. Take a form with one native input, one tea-field, and no button. Enter in the native input sends it, because the browser sees one text field. Enter in tea-field does nothing, because tea-field sees two. So give every form with more than one field a submit button, and the count never matters.
Why it matters: people press Enter to send. A field that presses the right button keeps its name, its value, and a disabled button's no.
How do you style every state of a web component input?
A field has more states than a button: hover, focus, filled, too long, an error showing, disabled, and readonly. The kit's finished field gives each one a look, in a light and a dark color scheme. Here they are side by side:
<link rel="stylesheet" href="tea-kit/tokens.css"><style> form { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } .day, .evening { display: grid; gap: 12px; padding: 8px; background: Canvas; color: CanvasText; } .day { color-scheme: light; } .evening { color-scheme: dark; }</style><form> <div class="day"> <tea-field maxlength="140"><span slot="label">Default</span></tea-field> <tea-field maxlength="140" value="Happy birthday"><span slot="label">Filled</span></tea-field> <tea-field maxlength="10" value="Happy birthday" class="tried"><span slot="label">Too long</span></tea-field> <tea-field maxlength="140" value="Happy birthday" disabled><span slot="label">Disabled</span></tea-field> <tea-field maxlength="140" value="Happy birthday" readonly><span slot="label">Readonly</span></tea-field> </div> <div class="evening"></div></form><script type="module"> document.querySelector(".evening").innerHTML = document.querySelector(".day").innerHTML; await import("./tea-kit/index.js"); for (const field of document.querySelectorAll(".tried")) field.checkValidity();</script>- Lines 4 to 6 make a day box with a light color scheme, and an evening box with a dark one.
- Lines 10 to 14 are five fields. Line 12 allows only 10 characters, so it's too long.
- Line 19 copies the day box into the evening box. Line 21 checks the too long fields once, so their error shows.
In the day box, the default border is dim gray, rgb(105, 105, 105), on white. In the evening box it's dark gray, rgb(169, 169, 169), on rgb(59, 59, 59). The error is firebrick, rgb(178, 34, 34), by day, and light coral, rgb(240, 128, 128), in the evening. Move the pointer over a box: its border takes the text color. Press Tab: the kit's green ring goes around the box.
Here is the field's CSS, from tea-kit/tea-field.js:
@layer base, component, state;
@layer component {
:host { --_quiet: light-dark(var(--tea-color-stone, dimgray), darkgray); --_error: light-dark(var(--tea-color-error, firebrick), lightcoral); }
label { display: block; margin-block-end: 4px; font-weight: bold; }
input { display: block; inline-size: 100%; padding: 4px 8px; border: 2px solid var(--_quiet); border-radius: var(--tea-radius, 8px); font: inherit; background: Field; color: FieldText; }
small { display: block; color: var(--_quiet); }
small:empty { display: none; }
::slotted([slot="hint"]), #count, #error { display: block; margin-block-start: 4px; }
#error { color: var(--_error); font-weight: bold; }
}
@layer state {
input:read-write:hover { border-color: currentColor; }
:host(:state(filled)) #count { color: inherit; }
:host(:state(too-long)) #count { color: var(--_error); font-weight: bold; }
:host(:state(user-invalid)) input { border-color: var(--_error); border-inline-start-width: 8px; padding-inline-start: 2px; }
:host([readonly]) input { border-style: dashed; }
:host(:disabled) { opacity: 0.5; }
@media (forced-colors: active) {
:host(:disabled) { opacity: 1; }
:host(:disabled) label, :host(:disabled) input, :host(:disabled) small { border-color: GrayText; color: GrayText; }
}
}- Line 3 makes two colors with
light-dark(), as in lesson 15.1. Each uses the kit's token in a light scheme, and a lighter color in a dark one (MDN). - Line 5 gives the box the browser's own field colors,
FieldandFieldText, which follow the scheme. - Line 12 is hover.
:read-writeleaves out a box that's readonly or disabled. - Lines 13 and 14 color the count: the text color once there's text, and the error color once it's too long.
- Line 15 marks an error with a thick border on the start side, as well as the color.
- Line 16 dashes a readonly box. Line 17 fades a disabled field.
- Lines 18 to 21 use GrayText for a disabled field in forced colors mode.
Three of the states are custom states, which the class sets (lesson 12.3, MDN): filled, too-long, and user-invalid. The last is lesson 16.3's. Chrome never matches :user-invalid on a custom element, as lesson 16.3 found. So the field uses :state(user-invalid).
Why the thick border? Color alone can't tell everyone about an error. In forced colors mode, the browser swaps your colors for the person's own. With Chrome's emulation, every border turns the same color, but the 8 px start border stays. The error's words say the rest.
Ravi's kettle has a small light. It's red while the water heats, and green when it's ready. The kettle switches the light itself. Anyone in the shop can see it from the counter, by day or at night.
- In real life: The kettle
- In JavaScript: tea-field
- In real life: It switches its own light on
- In JavaScript: The class adds a custom state
- In real life: Seeing the light from the counter
- In JavaScript: Page CSS reads :state()
- In real life: Easy to see by day and at night
- In JavaScript: light-dark() picks a color for each scheme
Read each row across: the state, the rule in the field's own CSS, and the rule a page can write.
| State | Inside the shadow root | On the page |
|---|---|---|
| The pointer is over the box. | input:read-write:hover | tea-field:hover |
| The box has focus. | input:focus-visible | tea-field:focus |
| The box has text. | :host(:state(filled)) | tea-field:state(filled) |
| The text is too long. | :host(:state(too-long)) | tea-field:state(too-long) |
| The error shows. | :host(:state(user-invalid)) | tea-field:state(user-invalid) |
| It's disabled, or in a disabled fieldset. | :host(:disabled) | tea-field:disabled |
| It's readonly. | :host([readonly]) | tea-field[readonly] |
Look at the focus row. A host that delegates focus matches :focus, but never :focus-visible, as lesson 14.1 found. So the field draws its ring on the box. A page restyles the parts with ::part(), like tea-field::part(error), and can join a state to a part, like tea-field:state(filled)::part(count). Exercises 4 and 6 do both.
Why it matters: people read a field's state before they type. Each state needs a look in every scheme, and more than color.
Adding a text field to the tea kit
The kit's new version, kitAfter173, adds tea-field. Here is Meena's order form with two fields, the switch, and the kit's buttons:
<link rel="stylesheet" href="tea-kit/tokens.css"><form id="order"> <tea-field name="who" required required-message="Enter the name for the order."><span slot="label">Name</span></tea-field> <tea-field name="message" maxlength="140"><span slot="label">Gift message</span><span slot="hint">We write it on the card by hand.</span></tea-field> <p><tea-toggle name="oat">Add oat milk</tea-toggle></p> <tea-button name="pay" value="counter">Place order</tea-button> <tea-button type="reset">Start over</tea-button></form><p>Asha's message: <q>Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha</q></p><script type="module"> import "./tea-kit/index.js"; const form = document.querySelector("#order"); form.addEventListener("submit", (event) => { event.preventDefault(); console.log("Sent:", new URLSearchParams(new FormData(form)).toString()); });</script>- Line 3 is Name. It's required, and
required-messagegives its own words. - Line 4 is the gift message, with a limit and a hint. Line 6 is Place order, a tea-button.
- Click in Name and press Enter. Enter presses Place order, and the form stops at Name: Enter the name for the order.
- Type Asha and press Enter:
Sent: who=Asha&message=&pay=counter. An empty gift message is fine. - Paste Asha's message into Gift message and press Enter. Nothing is sent: 11 characters too many, and Use 140 characters or less.
- Press Start over. Both fields are empty again.
Chrome's tree after step 1:
textbox "Name", focused, invalid, description: "Enter the name for the order."
textbox "Gift message", description: "We write it on the card by hand. 140 characters left"Here is the start of the class, from tea-kit/tea-field.js:
static formAssociated = true;
static observedAttributes = ["value", "maxlength", "required", "required-message", "readonly", "placeholder", "autocomplete"];
#internals = attachInternals(this);
#box;
#dirty = false;
#tried = false;
#pause;
constructor() {
super();
this.attachShadow({ mode: "open", delegatesFocus: true });
this.shadowRoot.adoptedStyleSheets = [base, sheet];
this.shadowRoot.append(template.content.cloneNode(true));
if (hasReferenceTarget) this.shadowRoot.referenceTarget = "box";
this.#box = this.shadowRoot.getElementById("box");
this.#box.addEventListener("input", () => {
this.#dirty = true;
this.#update();
this.#announce();
});
this.#box.addEventListener("change", () => this.dispatchEvent(new Event("change", { bubbles: true })));
this.#box.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
setTimeout(() => {
if (!event.defaultPrevented) pressEnter(this.#internals.form);
});
});
this.addEventListener("invalid", () => {
this.#tried = true;
this.#update();
});
this.#update();
}- Line 2 watches seven attributes, like value, maxlength, and required-message.
- Line 3 lists its internals for checkers like axe (lesson 15.3).
- Line 25 calls
pressEnter()from tea-kit/enter.js. It's the rule from the Enter section, shared with the search box. - Lines 28 to 31 show the error once the form has tried to send.
Further down, the field has three form callbacks from lesson 16.4. A reset brings back the value attribute. A disabled fieldset turns the box off. Back brings the text back. Without maxlength, it has no count and no limit. Without required-message, an empty required field uses the browser's own words, borrowed from an input that's never on the page. The JSDoc and custom-elements.json document every attribute, slot, part, state, and event.
kitAfter173 also changes the search box. Its Enter now calls pressEnter() too, so a disabled Search button stops it, as in a native box. The course's test runs pages from earlier lessons with kitAfter172 and kitAfter173: lessons 13.2, 15.3, 16.5, 17.1, and 17.2. Every printed line, box, color, and tree stays the same. Before you ship a field of your own, listen to it with a screen reader, as lesson 15.3 shows.
Why it matters: the kit's forms now have a text field that labels, checks, sends, and looks like the rest of the kit.
Common mix-ups
- "maxlength stops every long value." No. It stops typing and pasting. A script's value goes through, and the form sends it.
- "validity.tooLong tells you the text is too long." No. On an input it's true only after a person's edit leaves it too long, which maxlength mostly stops.
- "A page label and the field's own label can both stay." No. Through Reference Target, Chrome joins them: Gift message Gift message.
- "internals.labels always lists the page's label." No. With Reference Target, Chrome lists it in the inner box's labels.
- "Show the error as soon as the box loses focus." No. It can push Send down under the pointer, and the click misses.
- "Cancelling invalid only hides the bubble." No. Focus no longer moves to the field either.
- "requestSubmit() on Enter is what a native box does." No. A native box presses the first submit button, and stops if it's disabled.
- "The count should be a live region." No. That speaks after every key. Announce it after a pause.
- ":user-invalid styles a custom field after a failed send." No. Chrome never matches it on a custom element. Use a custom state.
- "Red is enough to show an error." No. Forced colors mode replaces it. Add a shape, like a thick border, and words.
Practice exercises
Predict the line this page prints, then run it.
<form>
<input name="tea" maxlength="5">
</form>
<script>
const form = document.querySelector("form");
form.elements.tea.value = "jasmine";
console.log(form.checkValidity(), new URLSearchParams(new FormData(form)).toString());
</script><form> <input name="tea" maxlength="5"></form><script> const form = document.querySelector("form"); form.elements.tea.value = "jasmine"; console.log(form.checkValidity(), new URLSearchParams(new FormData(form)).toString());</script>It prints true tea=jasmine. maxlength only stops typing and pasting, and only a person's edit can make the box too long. So the form is valid, and it sends all 7 characters.
Type Hi in Gift message. Predict what Enter prints, then press Enter.
<form> <tea-field name="message" maxlength="140"><span slot="label">Gift message</span></tea-field> <button hidden></button> <tea-button name="pay" value="card">Pay by card</tea-button></form><script type="module" src="tea-kit/index.js"></script><script src="tea-field.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); const sent = new URLSearchParams(new FormData(form, event.submitter)); console.log(`Sent ${sent} by ${event.submitter?.localName ?? "the form"}`); });</script><form> <tea-field name="message" maxlength="140"><span slot="label">Gift message</span></tea-field> <button hidden></button> <tea-button name="pay" value="card">Pay by card</tea-button></form><script type="module" src="tea-kit/index.js"></script><script src="tea-field.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); const sent = new URLSearchParams(new FormData(form, event.submitter)); console.log(`Sent ${sent} by ${event.submitter?.localName ?? "the form"}`); });</script>It prints Sent message=Hi by button. The hidden button on line 3 is the form's first submit button, so tea-field clicks it. Pay by card comes later, and isn't pressed.
This page throws a TypeError. Fix line 54 of the tea-field.js tab. What does the page print then?
<form> <tea-field name="message" maxlength="140"> <span slot="label">Gift message</span> </tea-field></form><script src="tea-field.js"></script><script> const form = document.querySelector("form"); const field = document.querySelector("tea-field"); field.value = "Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha"; form.checkValidity(); console.log(field.shadowRoot.querySelector("#error").textContent);</script><form> <tea-field name="message" maxlength="140"> <span slot="label">Gift message</span> </tea-field></form><script src="tea-field.js"></script><script> const form = document.querySelector("form"); const field = document.querySelector("tea-field"); field.value = "Happy birthday, Ravi! Thank you for every cup of jasmine tea this year. See you at Leaf and Kettle on Saturday for cake and a pot of oolong. Love, Asha"; form.checkValidity(); console.log(field.shadowRoot.querySelector("#error").textContent);</script>The page stays the same. In the tea-field.js tab, line 54 now passes the words and the box: setValidity({ tooLong: true }, Gift message must be ${max} characters or less., this.#box). The page prints Gift message must be 140 characters or less.
Write one rule on line 2 that hides the count of an empty field. What does the page print then?
<style> /* Hide the count of an empty field here. */</style><tea-field maxlength="140"><span slot="label">Gift message</span></tea-field><tea-field maxlength="140" value="Happy birthday"><span slot="label">Gift message</span></tea-field><script type="module"> await import("./tea-kit/index.js"); const [empty, filled] = document.querySelectorAll("tea-field"); const shown = (field) => getComputedStyle(field.shadowRoot.querySelector("[part=count]")).display; console.log(`Empty: ${shown(empty)}, filled: ${shown(filled)}`);</script><style> tea-field:not(:state(filled))::part(count) { display: none; }</style><tea-field maxlength="140"><span slot="label">Gift message</span></tea-field><tea-field maxlength="140" value="Happy birthday"><span slot="label">Gift message</span></tea-field><script type="module"> await import("./tea-kit/index.js"); const [empty, filled] = document.querySelectorAll("tea-field"); const shown = (field) => getComputedStyle(field.shadowRoot.querySelector("[part=count]")).display; console.log(`Empty: ${shown(empty)}, filled: ${shown(filled)}`);</script>Line 2 hides the count part of any field without the filled state. The empty field's count is hidden, and the filled one's still shows, so the page prints Empty: none, filled: block.
Type Hi and press Enter. The form sends without wrap=paper. Fix #enter() in the tea-field.js tab. What does Enter print then?
<form> <tea-field name="message" maxlength="140"><span slot="label">Gift message</span></tea-field> <button name="wrap" value="paper">Send</button></form><script src="tea-field.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); const sent = new URLSearchParams(new FormData(form, event.submitter)); console.log(`Sent ${sent} by ${event.submitter?.localName ?? "the form"}`); });</script><form> <tea-field name="message" maxlength="140"><span slot="label">Gift message</span></tea-field> <button name="wrap" value="paper">Send</button></form><script src="tea-field.js"></script><script> const form = document.querySelector("form"); form.addEventListener("submit", (event) => { event.preventDefault(); const sent = new URLSearchParams(new FormData(form, event.submitter)); console.log(`Sent ${sent} by ${event.submitter?.localName ?? "the form"}`); });</script>The page stays the same. In the tea-field.js tab, #enter() now finds Send, the first control whose type is submit, and clicks it. Send's name and value go too, and it's the submitter: Sent message=Hi&wrap=paper by button.
The evening box's error is firebrick on a dark background, hard to read. Fix line 4. What does the page print then?
<style> .day { color-scheme: light; } .evening { color-scheme: dark; background: Canvas; } tea-field::part(error) { color: firebrick; }</style><form> <div class="day"><tea-field maxlength="10" value="Happy birthday"><span slot="label">Day</span></tea-field></div> <div class="evening"><tea-field maxlength="10" value="Happy birthday"><span slot="label">Evening</span></tea-field></div></form><script type="module"> await import("./tea-kit/index.js"); const colors = [...document.querySelectorAll("tea-field")].map((field) => { field.checkValidity(); return getComputedStyle(field.shadowRoot.querySelector("[part=error]")).color; }); console.log(`Day: ${colors[0]}, evening: ${colors[1]}`);</script><style> .day { color-scheme: light; } .evening { color-scheme: dark; background: Canvas; } tea-field::part(error) { color: light-dark(firebrick, lightcoral); }</style><form> <div class="day"><tea-field maxlength="10" value="Happy birthday"><span slot="label">Day</span></tea-field></div> <div class="evening"><tea-field maxlength="10" value="Happy birthday"><span slot="label">Evening</span></tea-field></div></form><script type="module"> await import("./tea-kit/index.js"); const colors = [...document.querySelectorAll("tea-field")].map((field) => { field.checkValidity(); return getComputedStyle(field.shadowRoot.querySelector("[part=error]")).color; }); console.log(`Day: ${colors[0]}, evening: ${colors[1]}`);</script>Line 4 now uses light-dark(firebrick, lightcoral). The evening box has a dark color scheme, which reaches the part, so its error turns light coral: Day: rgb(178, 34, 34), evening: rgb(240, 128, 128).
Check your understanding
Question 1 of 8What does this maxlength page print?
Read the code, then predict<input maxlength="5"> <script> const box = document.querySelector("input"); box.value = "jasmine"; console.log(box.value.length, box.validity.tooLong); </script>Choose an answer to see the explanation.
Question 2 of 8Asha pastes 151 characters into <input maxlength="140">. What does Chrome do?
Choose an answer to see the explanation.
Question 3 of 8A page writes <label for="gift"> for a tea-field whose label slot also says Gift message. With Reference Target and no fix, what is the box named?
Choose an answer to see the explanation.
Question 4 of 8A page cancels tea-field's invalid event. What happens when a send fails?
Choose an answer to see the explanation.
Question 5 of 8A form has tea-field and a disabled Send button. What does Enter in tea-field do?
Choose an answer to see the explanation.
Question 6 of 8Why does tea-field wait for a failed send before it shows its error?
Choose an answer to see the explanation.
Question 7 of 8Which rule styles tea-field from the page once its error shows?
Choose an answer to see the explanation.
Question 8 of 8In a box with color-scheme: dark, what color does light-dark(var(--tea-color-error, firebrick), lightcoral) give the error?
Choose an answer to see the explanation.
Key takeaways
- A text input web component wraps a real input. Its label, hint, count, and error share one shadow root, so plain ids name and describe the box.
- Give the box one label. A page label plus the field's own makes Chrome say the name twice, so drop one.
- maxlength cuts what people type and paste, and never flags a script's value. Count the text yourself and set
tooLongwith your own words. - Word each error by what went wrong and how to fix it. Show it after a failed send, and remove it once it's fixed.
- Keep Chrome's bubble, or move focus yourself. Announce the count after a pause, not on every key.
- On Enter, press the form's first submit button unless it's disabled. With none, send only a form with one text field.
- Style every state with custom states and parts, in light and dark with
light-dark(), and with more than color for forced colors mode.
Remember the one-liner.
A web component input keeps a real box with its label and messages. It checks its own rules in its own words, presses the right button on Enter, and shows every state.
Sources
The facts on this page come from these standards, docs, source files, and guides:
- Limiting user input length: the maxlength attribute, HTML Standard.
- ValidityState: tooLong property, MDN.
- Element: attachShadow() method, MDN.
- ElementInternals: labels property, MDN.
- Chrome 152 release notes: Reference Target for cross-root ARIA, Chrome for Developers.
- Character count, GOV.UK Design System.
- ElementInternals: setValidity() method, MDN.
- The validation anchor, HTML Standard.
- Error message, GOV.UK Design System.
- validation_message_client_impl.cc at 158.0.8127.18: DidChangeFocusTo(), Chromium.
- Interactively validate the constraints, HTML Standard.
- Element: ariaNotify() method, MDN.
- Implicit submission, HTML Standard.
- HTMLFormElement: requestSubmit() method, MDN.
- submit-on-enter.ts at 9166643c: submitForm(), Web Awesome.
- CustomStateSet, MDN.
- :state(), MDN.
- :user-invalid, MDN.
- light-dark(), MDN.
- forced-colors, MDN.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: A base class for form controls. It pulls the form code that the switch, the button, and the field share into one class they can all extend.