beforeinput Gates Rich Text Edits

The beforeinput event carries an inputType for the pending edit, so a contenteditable can preventDefault formatting commands before they land.

JavascriptForm Validation

Code

javascriptsnippet
20 lines
const editor = document.querySelector('[contenteditable]');

// beforeinput fires before the edit lands; inputType names the edit
const allowed = new Set([
  'insertText',
  'deleteContentBackward',
  'deleteContentForward',
  'insertParagraph',
]);

editor.addEventListener('beforeinput', (event) => {
  if (!allowed.has(event.inputType)) {
    event.preventDefault();
    console.log('blocked edit:', event.inputType);
  }
});

editor.addEventListener('input', () => {
  console.log('text now:', editor.textContent);
});

How it works

Demo state sits in top-level bindings: editor, allowed.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Using it

The demo output is labeled (blocked edit:, text now:), so every line of output can be traced to the operation that made it.

The key statements, annotated

editor.addEventListener('beforeinput', (event) => {
  if (!allowed.has(event.inputType)) {
    event.preventDefault();
    console.log('blocked edit:', event.inputType);
  }
});
editor.addEventListener('input', () => {
  console.log('text now:', editor.textContent);
});
const allowed = new Set([
  'insertText',
  'deleteContentBackward',
  'deleteContentForward',
  'insertParagraph',
]);

Interactive Tools for This Topic

FAQ

Does beforeinput Gates Rich Text Edits 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.