Skip to content
Advertisement

How prevent whitespace in input field with plain 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);
});

Advertisement

Answer

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);
};
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement