如何防止在文本输入框和文本区域中输入连续的两个空格?

huangapple go评论49阅读模式
英文:

How can I prevent 2 spaces in a row being entered in text input and textarea?

问题

我想防止连续输入两个空格。
目前,对于姓名,您可以使用所有的空格。
我希望多个单词之间只有一个空格,但不要超过一个空格在一起。
此外,如果文本被复制并粘贴,还可能防止多个空格?

我强制输入3个字符,但在我的表单中它们都可以是空格,除非我使用这个代码,但它会停止所有的空格。我只想允许单词之间有一个空格:

我找到了一种停止所有空格的方法,但在尝试其他方法时丢失了代码。我可以再找到它,但这并不完全是我想要的。我知道肯定有一个简单的方法,而且我不可能是唯一一个需要的人。请有人能帮帮我吗?

英文:

I want to prevent 2 spaces from being entered consecutively.
Right now, for a name, you can use all spaces.
I want multiple words with 1 space in-between each word, but not more than 1 space together.
Also, possibly even prevent multiple spaces if the text was copied and pasted in?

I force 3 characters but they can all be spaces in my form unless I use this code but it stops all spaces. I want to allow only 1 space between words. :

<input type="text" name="name" placeholder="Required...." 
  minlength="3" maxlength="40" required 
  oninvalid="this.setCustomValidity('Please enter a name with at least 3 characters.')" 
  oninput="setCustomValidity('')" 
  onKeyDown="javascript: var keycode = keyPressed(event); if(keycode==32){ return false; }" 
/>

I found a way to stop all spaces but I lost the code trying other things. I could find it again but it is not exactly what I want. I know there must be a simple way, and I can't be the only one who wants it.
Can someone please help me?

答案1

得分: 1

根据我的示例,您可以看到我链接的代码也适用于 oninput

document.querySelector('input').addEventListener('input', (e) => {
   e.target.value = e.target.value.replace(/  +/g, ' ');
});
document.querySelector('input').addEventListener('change', (e) => {
   e.target.value = e.target.value.replace(/  +/g, ' ');
});
<input type="text">

以上是您要翻译的内容。

英文:

As you can see from my example the code i linked work with oninput too

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.querySelector(&#39;input&#39;).addEventListener(&#39;input&#39;, (e) =&gt; {
   e.target.value = e.target.value.replace( /  +/g, &#39; &#39; );
});
document.querySelector(&#39;input&#39;).addEventListener(&#39;change&#39;, (e) =&gt; {
   e.target.value = e.target.value.replace( /  +/g, &#39; &#39; );
});

<!-- language: lang-html -->

&lt;input type=&quot;text&quot;&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月6日 17:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76413080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定