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
data
object contains two properties:myString
andoutput
.myString
is the value of the input field, andoutput
is the message that will be displayed to the user. - The
checkString
method is called whenever the input field is changed (using the@input
event). It checks whether the value ofmyString
is 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
output
property is set to the message “String is empty or contains only spaces!”. Otherwise, theoutput
property 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>