User input validation is one of the most important part of any form on the web. Luckily, with Vue.js, you can easily validate the entered text by the user as they type and only allow what’s valid. That is, you’ll be able to automatically remove any special characters entered by the user as they type in something. Earlier, I’ve written an article on how you can remove special characters from a string in JavaScript. And here’s an example on how you can achieve the same in Vue.js:
<template>
<div id="app">
<div>
<h4>Please type some special characters to check</h4>
<input type="text" placeholder="Type in here" v-model="inputValue" />
</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
inputValue: "",
};
},
watch: {
inputValue(newValue) {
this.inputValue = this.removeSpecialCharacters(newValue);
},
},
methods: {
removeSpecialCharacters(charactersString) {
return charactersString.replace(/[^\w\s]/gi, "");
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
</style>
Code language: HTML, XML (xml)
In the above code, I’ve added an observer to the local state named inputValue.
Whenever the value of this state changes, it calls the removeSpecialCharacters() method. It can replace any special characters it finds with an empty character. The result then replaces the original state (in this case, inputValue).
Please note that, it means that even when it replaces the result with every key stroke, the component is still going to be re-rendered. And that re-render would be continuously called on every key stroke even if the entered stroke does NOT have a special character. To avoid this, you can first check if the entered input has any special character, and if there is, you can then replace it with a result containing no special characters. By calling the removeSpecialCharacters() method, of course. The modified methods would then look like:
//...
watch: {
inputValue(newValue) {
if (this.checkForSpecialCharacters(newValue)) {
this.inputValue = this.removeSpecialCharacters(newValue);
}
},
},
methods: {
removeSpecialCharacters(charactersString) {
return charactersString.replace(/[^\w\s]/gi, "");
},
checkForSpecialCharacters(charactersString) {
const specialCharactersRegex = /[^\w\s]/;
return specialCharactersRegex.test(charactersString);
},
},
//...
Code language: JavaScript (javascript)
You can find a working copy of the above code from my repos below:
If you have any doubts or suggestions, sound off in the comments below!