Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mvnobrega's avatar

Prevent white space in the input not working

I need to prevent my users from placing the "username" with spaces between words.

I solved it this way:

<input @keydown.space.prevent type="text" v-model:value="username">

But @keydown.space.prevent doesn't work on mobile devices or when the user copies and pastes a text.

What better way to solve this?

0 likes
4 replies
bugsysha's avatar

You should use validation for this. Probably something like

<input type="text" v-model:value="username" pattern="[A-Za-z0-9]+">

Also you can do following:

<input type="text" v-model:value="username" pattern="[A-Za-z0-9]+" onkeydown="if(['Space'].includes(arguments[0].code)){return false;}">
1 like
piljac1's avatar
piljac1
Best Answer
Level 28

I've already encountered issues when using patterns, but I believe it was when matching a pattern with the number type and only on some mobile devices. In your case, it shouldn't be an issue imo.

If it is (or becomes) one, you can simply handle input suppression with Vue using v-model and a watcher. After the v-model sets the data property, the watcher is triggered and cleanup can be made (all this process is not visible to the end user, it feels the same as a keydown suppression).

watch: {
  username(value) {
    this.username = value.replace(/ +/g, '');
  }
}

You can complexify the regex pattern to reach the desired validation.

1 like
Phread's avatar

JavaScript to allow numbers only. It will NOT allow for spaces.

    <SCRIPT TYPE="text/javascript">
        <!--
        function numbersonly(myfield, e, dec)
        {
            var key;
            var keychar;
            if (window.event)
                key = window.event.keyCode;
            else if (e)
                key = e.which;
            else
                return true;
            keychar = String.fromCharCode(key);
            // control keys
            if ((key==null) || (key==0) || (key==8) ||
                (key==9) || (key==13) || (key==27) )
                return true;
            // numbers
            else if ((("0123456789").indexOf(keychar) > -1))
                return true;
            // decimal point jump
            else if (dec && (keychar == "."))
            {
                myfield.form.elements[dec].focus();
                return false;
            }
            else
                return false;
        }
        //-->
    </SCRIPT>

On the field

onkeypress="return restrictInput(this, event, integerCommaOnly);"

Please or to participate in this conversation.