Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How prevent whitespace in input field with plain javascript

Tags:

javascript

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);
});
like image 286
Alexandre Thebaldi Avatar asked Sep 03 '15 03:09

Alexandre Thebaldi


2 Answers

Use event.preventDefault to prevent its default behavior.

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 onkeypress of the input instead, jsfiddle

field.onkeypress = function(e) {
   var  key = e.keyCode;
   return (key !== 32);
};
like image 165
fuyushimoya Avatar answered Oct 24 '22 21:10

fuyushimoya


In case anyone needs this to be done which will replace all whitespace automatically and will not allow user to put space and will force them to put username without space even then copy paste . Here is the code.

<script type="text/javascript">
var field = document.querySelector('[name="username"]');

field.addEventListener('keyup', function ( event ) {  
   var userName = field.value;
  userName = userName.replace(/\s/g, '');
  field.value = userName;
});

</script>
like image 43
Md. Amanur Rahman Avatar answered Oct 24 '22 21:10

Md. Amanur Rahman