Vue Js check empty String and Space:In Vue.js, you can use the not operator (!) along with a regular expression (regex) to check if a string is empty or contains only spaces.
The regex pattern /\S/ matches any non-whitespace character, so using ! in front of it will check if the string contains no non-whitespace characters, which means it is either empty or only contains spaces
How can Vue.js check if a string is empty or contains only whitespace characters?
This code uses Vue.js to create a simple input field that checks whether the input is an empty string or contains only whitespace. Here’s how it works:
- The
dataobject contains two properties:myStringandoutput.myStringis the value of the input field, andoutputis the message that will be displayed to the user. - The
checkStringmethod is called whenever the input field is changed (using the@inputevent). It checks whether the value ofmyStringis falsy (i.e., empty or undefined) or if it contains only whitespace characters (using a regular expression). - If the input is empty or contains only spaces, the
outputproperty is set to the message “String is empty or contains only spaces!”. Otherwise, theoutputproperty is set to the message “String contains some content!”
Vue Js check empty String and Space Example
<div id="app">
<input type="text" v-model="myString" @input="checkString" />
<p>{{output}}</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
myString: "",
output: ''
};
},
methods: {
checkString() {
if (!this.myString || /^\s*$/.test(this.myString)) {
this.output = "String is empty or contains only spaces!";
} else {
this.output = "String contains some content!";
}
}
}
})app.mount('#app')
</script>
Output of Vue Js check empty String and Space



