paste Event Reads Clipboard Text

Read pasted clipboard text from clipboardData, normalize it, and reject values that fail the input's expected shape before they land.

JavascriptForm Validation

Code

javascriptsnippet
22 lines
// paste fires before the text lands in the field, and the payload
// rides on event.clipboardData — so the input can validate and
// normalize clipboard text before accepting it
const skuField = document.querySelector('#sku');
const hint = document.querySelector('#sku-hint');

skuField.addEventListener('paste', (event) => {
  const pasted = event.clipboardData.getData('text/plain');
  const normalized = pasted.trim().toUpperCase().replace(/\s+/g, '');

  // Backend expects the shape AB-1234
  if (!/^[A-Z]{2}-\d{4}$/.test(normalized)) {
    event.preventDefault();
    hint.textContent = 'SKU must look like AB-1234';
    hint.hidden = false;
    return;
  }

  event.preventDefault();
  skuField.value = normalized;
  hint.hidden = true;
});

Intercepting the paste before it lands

The paste event fires before text reaches the field, and the payload rides on event.clipboardData.getData('text/plain'). The handler normalizes immediately — pasted.trim().toUpperCase().replace(/\s+/g, '') — then tests the result against /^[A-Z]{2}-\d{4}$/, the AB-1234 shape the backend expects.

Both branches call preventDefault

A failing match shows the hint (hint.textContent = 'SKU must look like AB-1234', hint.hidden = false) and cancels the paste, so nothing malformed enters #sku. A passing match also calls event.preventDefault() — then writes the normalized value itself with skuField.value = normalized and hides the hint with hint.hidden = true. Preventing the default in both cases puts the handler, not the browser, in charge of the final field value.

The line that decides the shape

if (!/^[A-Z]{2}-\d{4}$/.test(normalized)) {
  event.preventDefault();

Everything downstream — the hint text, the hidden flag, the field value — follows from this one regex decision.

Interactive Tools for This Topic

FAQ

Does paste Event Reads Clipboard Text 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.