Datalist Combobox With Validity Guard

input.list exposes the bound datalist element and datalist.options enumerates suggestions, so free-typed values get a manual membership check.

TypescriptForm Validation

Code

typescriptsnippet
16 lines
const input = document.querySelector<HTMLInputElement>('input[list]');
const datalist = document.querySelector<HTMLDataListElement>('datalist');
if (!input || !datalist) throw new Error('combobox markup missing');

// input.list exposes the bound datalist element
console.log('list bound to:', input.list === datalist);
const options = Array.from(datalist.options).map((option) => option.value);
console.log('options:', options.join(', '));

// Free typing is allowed; membership against the option list is manual
const value = input.value.trim();
console.log('typed value:', value, 'known:', options.includes(value));
if (!options.includes(value)) {
  input.setAttribute('aria-invalid', 'true');
}
console.log('aria-invalid:', input.getAttribute('aria-invalid'));

How it works

The failure path is explicit — Error is raised when the guard condition holds.

The file’s state is a handful of top-level bindings: input, datalist, options, value.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard !input || !datalist stops the pass immediately with an early throw when its condition holds.

Using it

Look for the list bound to:, options:, typed value: prefixes once the file starts running; each one ties a printed line to the step that produced it.

Key statements

const options = Array.from(datalist.options).map((option) => option.value);
if (!input || !datalist) throw new Error('combobox markup missing');

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
`Error` is raised at the guard (`!input || !datalist`), so invalid state never reaches the main logic.
Does Datalist Combobox With Validity Guard run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.