9

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);
});

7 Answers 7

18

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);
};
Sign up to request clarification or add additional context in comments.

2 Comments

That is not enough when content come from a copy-paste, or when the textbox is auto-filled by the browser.
This doesn't prevent whitespace at all. It prevents the space key only. There are like 45 other ways the input can get whitespace.
4

Modify the input like:

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

Then the javascript is:

<script type="text/javascript">

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

Comments

2

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?

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

2 Comments

Just saw the answer by @fuyushimoya, it would probably be good anyways to check for the different kinds of whitespaces
so it doesn't work in android mobile. When someone using an android mobile to register then he can put space in the user name. So how to stop that ? I think instead of key value we should do something new like replacing spaces. also copy past with space can escape this system
2

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>

Comments

0
        const key = e.keyCode
        const keyCodes = [
          32, 160, 5760, 8192, 8192, 8194, 8195, 8196, 8197, 8198, 8199,
          8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288,
        ]
        if (keyCodes.some((val) => val === key)) {
          e.preventDefault()
        }

here is a simple solution !

Comments

0

Hey i have simple solution regarding your question try one

If you want to submit only text and whitespace than use this one

<input type="text" name="Name" required pattern="[a-zA-Z ]+" >

If you want to submit number and whitespace than use this one

<input type="text" name="Name" required pattern="[0-9 ]+" >

If you want to insert text not whitespace than use this one

<input type="text" name="Name" required pattern="[a-zA-Z]+" >

Use any line according to your requirements no extra line of code or condition simple and secure

Comments

-1

HTML only solution using the pattern attribute and regex.

<form>
 <input type="text" name="username" pattern="[^\s]+">
 <button type="submit">Submit</button>
</form>

2 Comments

This works for input tag, but doesn't work for textarea tag.
Well, OP asked for an input field solution and this is by far simpler than the other answers suggesting Javascript. But anyway, thanks for the downvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.