英文:
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('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, ' ' );
});
<!-- language: lang-html -->
<input type="text">
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论