VueJS - disable space in input text

12,092

Solution 1

You can directly prevent that the user adds a white space to your input field. preventDefault() tells the user agent that the default action should not be taken as it normally would be.

<input @keydown.space="(event) => event.preventDefault()">

Or to make it even shorter (as Sovalina pointed out):

<input @keydown.space.prevent>

Solution 2

@keydown.native.space didn't work for me. @keydown.native.space.prevent did.

Solution 3

To prevent spaces on all input events - keypress, paste or drag and drop text:

const removeEventSpaces = e => {
  e.preventDefault();
  const left    = e.target.value.substring(0, e.target.selectionStart);
  const right   = e.target.value.substring(e.target.selectionEnd, e.target.value.length);
  const pasted  = (e.dataTransfer || e.clipboardData).getData('text').replace(/ /g, '');
  e.target.value = left + pasted + right;
}

<input @keydown.space.prevent @paste="removeEventSpaces" @drop="removeEventSpaces"/>

Solution 4

In this case, you can use Regular Expressions

value.replace(/\s/, '')

or to be sure the data is stored without any capital letters

value.replace(/\s/, '').toLowerCase()
Share:
12,092

Related videos on Youtube

1aliff
Author by

1aliff

Updated on July 05, 2022

Comments

  • 1aliff
    1aliff almost 2 years

    I have a component called TextInput.vue, and inside I created a div.

    <div ts-text-input :ts-text-input-filled="setFilledAttribute && !!value"
    :ts-text-input-not-valid="!valueValid">
    
    <input :value="value" @input="setValue" @keyup.enter="enterClicked" :placeholder="placeholder" :title="title">
    

    what I wanted to do now is that to disable some spaces inside the input box so that the user is unable to type in with spaces/spacebar (like, e.g., username input box)

    Here is what I have done; I try to use the function trim(), but it seems I can't still fix it.

    in the computed function

        computed: {
      value: function() {
        const {valueGetter, valueGetterOptions} = this,
          getter = this.$store.getters[valueGetter];
          value.trim();
        return valueGetterOptions ? getter(valueGetterOptions) : getter;
      },
    

    Any hints would be helpful. thanks. (sorry for my bad English)

  • Sovalina
    Sovalina over 5 years
    you also can write like this: <input @keydown.space.prevent>. Your answer is very clever btw
  • Jns
    Jns over 5 years
    Thanks for the advice!
  • 1aliff
    1aliff over 5 years
    oh yea! i knew it can be done something very simple like this! but i really had no idea. I tried both of the code, both are actually do the job. Thanks a lot! :)
  • Lukasz Wiktor
    Lukasz Wiktor about 5 years
    Does not prevent from pasting text with spaces.
  • fredrivett
    fredrivett about 4 years
    this will be because you're using it on a custom component, but it's a good point for those that are confused as to why this isn't working