There are times when we need to check if an input contains any special character. We might need to do so to prevent the user from entering invalid characters. Or to allow special characters in a field.
Here’s the example code that checks for the same:
<template>
<div id="app">
<input
type="text"
placeholder="Type something..."
v-model="inputValue"
@keyup="inputContainsSpecialCharacters"
/>
<p>
Contains special character:
<span v-if="inputContainsSpecialCharacter">✅ True</span>
<span v-else>❌ False</span>
</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
inputValue: null,
inputContainsSpecialCharacter: false,
};
},
methods: {
inputContainsSpecialCharacters() {
const specialCharacters = /[`!@#$%^&*()_+\-=\\|,.<>?~]/;
this.inputContainsSpecialCharacter = specialCharacters.test(
this.inputValue
);
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #000000;
margin-top: 60px;
}
input {
font-size: 16px;
padding: 4px;
border: 1px solid rgb(34, 34, 34);
outline: none;
}
</style>
Code language: HTML, XML (xml)
In the above code, we’ve bound an input element with a reactive state inputValue. Whenever there’s a keyup event in the input field, we call the inputContainsSpecialCharacters method. We’ve declared this method on line 27. It uses regex to check whether or not the input value contains any special character. If it does, we set the truthy value to inputContainsSpecialCharacter reactive state.
We’ve then checked whether it’s true or false. And based on that, we show two different messages in each case as in lines 11-12.
Here’s what the above code would look like in action:
You can find a working version of the above code from my repo links below: