如何只允许在输入中粘贴URL?

问题描述

我想要的是只允许对包含http和https的url进行粘贴,如果粘贴不包含http或https,那么我就不想粘贴任何内容

有什么建议吗?

解决方法

尝试一下:

element.addEventListener('paste',(e) => {
    e.preventDefault();
    const text = (e.originalEvent || e).clipboardData.getData('text/plain');
    if(/^http/.test(text)) {
      window.document.execCommand('insertText',false,text);
    }   
});

Codesandbox示例: https://codesandbox.io/s/brave-thompson-wtvvo?file=/src/index.js:59-75

,

您要做的是检查粘贴内容是否与所需内容匹配,如果粘贴不匹配,请阻止粘贴。

您将要在网址字段上附加event listener,并在发生粘贴事件时测试剪贴板内容。

您可以通过调用事件侦听器正在处理的事件对象上的剪贴板数据paste event,从getData("text/plain")中获取剪贴板内容的文本。
let data = e.clipboardData.getData("text/plain");

要测试此数据是否符合您的要求,可以使用正则表达式/^https?:\/\/.*$/

^与文本的开始匹配-粘贴数据必须开始以“ http”开头
http完全匹配“ http”
s?s匹配(可选)-因此https?将“ http”与后跟可选的“ s”匹配
:\/\/与冒号斜杠://匹配,但是/在正则表达式中表示某些内容,因此必须使用反斜杠\
对其进行转义。 .*$匹配所有其他内容,直到文本$

的末尾

如果剪贴板数据与您要允许粘贴的数据匹配;如果不匹配,您要通过调用event.preventDefault()

来阻止事件的默认粘贴行为

因此,您在此处获得URL字段document.getElementById('url-field')(假设该字段的 id url-field),并且您附加了事件监听器,收听paste事件。

我已经将输入字段设置为type="url"字段,尽管这也可以与type="text"一起使用,但您可以通过特别指定 url 来获得一些好处。
url字段也可以接受类似ftp://example.com/path/filename.txt之类的内容,因此您仍然仍然希望粘贴代码。

在字段本身上添加验证模式pattern="^https?://.*$",这样,如果您键入(而不是粘贴)没有http的内容,它也视为无效。

document.getElementById('url-field')
  .addEventListener('paste',e => {
      let data = e.clipboardData.getData("text/plain");
      let matched = /^https?:\/\/.*$/.test(data);
      //console.log('data:',data);
      //console.log('matched =',matched);
      if (! matched) {
        e.preventDefault();
      }
      // -or- putting everything inline,without extra variables
      /*
      if (!/^https?:\/\/.*$/.test(
          e.clipboardData.getData("text/plain")))
      {
          e.preventDefault();
      }
      */
  });
input:invalid {
  border-color: red;
}
div.field {
  margin-bottom: 0.5em;
}
<form>
  <div class="field">
    <label>Paste the URL:
     <input type="url" id="url-field" pattern="^https?://.*$">
   </label>
  </div>
  <div class="field">
    <label>Something else:
     <input type="text" id="notTheUrl">
   </label>
  </div>
</form>

现在,如果您有多个URL字段,并且想在所有这些URL字段上使用此“粘贴规则”,则可以使用querySelectorAll(...)代替getElementById(...),然后附加粘贴处理程序(使用.forEach每个字段(我们将在其他时间进行事件委托)

document.querySelectorAll('input[type=url]')
    .forEach(element => {
      element.addEventListener('paste',e => {
        if (!/^https?:\/\/.*$/.test(
            e.clipboardData.getData("text/plain")))
        { 
          e.preventDefault();
        }
      });
    });
input:invalid {
  border-color: red;
}
div.field {
  margin-bottom: 0.5em;
}
<form>
  <div class="field">
    <label>Paste the URL
     <input type="url" pattern="^https?://.*$">
   </label>
  </div>
  <div class="field">
    <label>Something else
     <input type="text" id="notTheUrl">
   </label>
  </div>
  <div class="field">
    <label>Another URL
     <input type="url" id="do-not-need-an-id" pattern="^https?://.*$">
   </label>
  </div>
</form>