javascript 如何使用纯javascript防止输入字段中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32366300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:09:42  来源:igfitidea点击:

How prevent whitespace in input field with plain javascript

javascript

提问by Alexandre Thebaldi

I have an username input field and trying to prevent user fill them with white spaces.

我有一个用户名输入字段并试图阻止用户用空格填充它们。

<input type="text" name="username" />

i do this and whitespace isn't blocked

我这样做并且空格没有被阻止

var
  field = document.querySelector('[name="username"]');

field.addEventListener('keypress', function ( event ) {  
   var 
     key = event.keyCode;

   return (key !== 32);
});

回答by fuyushimoya

Use event.preventDefaultto prevent its default behavior.

使用event.preventDefault来防止其默认行为。

var field = document.querySelector('[name="username"]');

field.addEventListener('keypress', function ( event ) {  
   var key = event.keyCode;
    if (key === 32) {
      event.preventDefault();
    }
});
<input type="text" name="username" />

If you want to use the return false;, then you should use the onkeypressof the input instead, jsfiddle

如果你想使用return false;,那么你应该使用onkeypress输入的 ,jsfiddle

field.onkeypress = function(e) {
   var  key = e.keyCode;
   return (key !== 32);
};

回答by Mr. B

Modify the input like:

修改输入,如:

<input type="text" name="username" onkeypress="CheckSpace(event)"/>

Then the javascript is:

然后javascript是:

<script type="text/javascript">

function CheckSpace(event)
{
   if(event.which ==32)
   {
      event.preventDefault();
      return false;
   }
}

回答by Keith M

Try checking for all the different kinds of whitespaces listed here Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

尝试检查此处列出的所有不同类型的空格是否还有其他空格代码,例如   表示半空格、em-空格、en-空格等在 HTML 中有用?

So you code would be:

所以你的代码是:

var field = document.querySelector('[name="username"]');

field.addEventListener('keypress', function ( event ) {  
   var 
   key = event.keyCode;

   return (key !== 32 && key !== 160 && key != 5760 && key != 8192 && key != 8192 && key != 8194 && key != 8195 && key != 8196 && key != 8197 && key != 8198 && key != 8199 && key != 8200 && key != 8201 && key != 8202 && key != 8232 && key != 8233 && key != 8239 && key != 8287 && key != 12288);
});

Here is the complete list of all the different kinds of whitespaces: https://en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode

以下是所有不同类型空格的完整列表:https: //en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode