VueJS - disable space in input text
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()
Related videos on Youtube
1aliff
Updated on July 05, 2022Comments
-
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 over 5 yearsyou also can write like this:
<input @keydown.space.prevent>
. Your answer is very clever btw -
Jns over 5 yearsThanks for the advice!
-
1aliff over 5 yearsoh 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 about 5 yearsDoes not prevent from pasting text with spaces.
-
fredrivett about 4 yearsthis 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