What's the best way to implement text-character restrictions in Vue JS ? I am looking to achieve with RegExp so that the user will not be allowed to type the symbols in the field.
I use a two pronged approach:
First is to use a watch
or computed
value with a setter, as Daniel recommends above. Besides handling keyboard input, it also handles input via drag and drop, paste, or whatever else the user comes up with.
Second is a keydown
handler. When using only a watched value, there is a slight delay in the UI. The restricted character is briefly displayed before being removed. For a more seamless user experience, the keydown
listener cancels the keyboard event for invalid input.
new Vue({
el: "#app",
data: {
name: "",
},
watch: {
name(val) {
this.name = val.replace(/\W/g, "");
},
},
methods: {
nameKeydown(e) {
if (/^\W$/.test(e.key)) {
e.preventDefault();
}
},
},
});
html {
font-family: sans-serif;
}
.demo {
display: flex;
justify-content: space-between;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<main id="app">
<p>Try typing spaces, punctuation, or special characters into each box to see the difference made by the key handler.</p>
<div class="demo">
<div>
<div>Without key handler:</div>
<input type="text" v-model="name" />
</div>
<div>
<div>With key handler:</div>
<input type="text" v-model="name" @keydown="nameKeydown($event)" />
</div>
</div>
</main>