← 中文资源

简体中文版本

paste 事件读取剪贴板文本

在输入框上监听 paste,从 clipboardData 拿到剪贴板文本,先规范化再校验格式,不符合就直接 preventDefault 拦下这次粘贴。

阅读英文原文

实现说明

顶层就这几处状态:skuField、hint。

使用要点

  • 用到了 document,需要在浏览器环境运行,Node 里直接跑会缺 API。

常见问题

「paste 事件读取剪贴板文本」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

const normalized = pasted.trim().toUpperCase().replace(/\s+/g, '');

代码示例

// 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;
});