Watchers: How to use it for form input validation in Vue JS

What are watchers in Vue?

Vue.js ships with the watch option just like the computed methods and data option. Watchers offer a great way to respond to data changes in a given element. The watch option is also a very powerful tool for conducting form validation.

Prerequisites of using watchers

Vue.js enables developers to create forms in Vue applications just as they would with HTML5. That means little to no additional skills are required to build forms in the Vue template section of any component with plain HTML.

This tutorial of watchers is suited for developers at all stages, including beginners. Below are a few things you should already have before going through this watchers tutorial.

  • Node.js version 10.x and above installed (you can verify whether you have it by running the following command in your terminal/command prompt:node -v
  • A code editor 
  • Vue’s latest version installed globally on your machine
  • Vue CLI 3.0 installed on your machine.
    • To do this, uninstall the old CLI version firstnpm uninstall -g vue-cli
    • Then, install the new onenpm install -g @vue/cli
    • Download a Vue starter project
    • Unzip the downloaded project
    • Navigate into the unzipped file and run the command below to keep all the dependencies up to datenpm install

Using Vue devtools

Throughout this tutorial, we’ll inspect our code with Vue devtools, a browser extension developers use to debug their Vue projects. You can filter components, select components right inside the UI, inspect the DOM, and filter inspected data. The extension also ships with some cool switching tabs such as switch to Vuex, switch to components, switch to events, routing, performance, and settings.

Vue Devtools

What we’ll build

To illustrate how to use the Vue watch option to handle form input validation, we’ll build a “create a new account” form that will contain fields for the user to enter their email and password.

Above all, you should have already downloaded the canvas project. That is to say, open the project in your IDE, go into the component folder. After that, replace the content of your Test.vue file with the code block below.

<template>
<div id="visa">
<h1>Create a New Vue Account</h1>
<form>
<label for="full name">Full Name:</label>
<input type="text" v-model="name" required>
<br>
<label for="email">Email Address:</label>
<input type="text" v-model="email" required>
<br> <label for="password">Password:</label>
<input type="text" v-model="password" required> <label for="twitter">Twitter Handle:</label>
<input type="text" v-model="twitter" required>
</form>
</div>
</template>
<script>
export default {
name: 'Test',
props: {
msg: String
},
data(){
return {
name: '',
password: '',
email: '',
twitter: ''
}
}
}
</script>
<style scoped>
#visa {
margin: 20px auto;
max-width: 700px;
margin-bottom: 28px;
}
label{
display: block;
margin: 20px 0 10px;
}
span {
padding-top: 0px;
margin-top: 0px;
font-size: 12px; color:red;
}
input {
font-size: 30px;
border: 1px double rgb(102, 97, 96) ;
border-radius: 4px;
}
</style>

To clarify, this creates the form with Vue input binding. So, you can see it in action in the browser using the Vue devtools extension.

watchers

Email validation

For the email input, we only want users to enter valid emails like (e.g., “johnDoe@gmail.com”). Fortunately, there are JavaScript functions that can check for that. So, we’ll use the watch option to trigger the function for the input to be checked.

Replace your template section with the code block below.

<template> 
<div id="visa">
<h1>Create a New Vue Account</h1>
<form>
<label for="full name">Full Name:</label>
<input type="text" v-model="name" required>
<br>
<label for="email">Email Address:</label>
<input type="text" v-model="email" required> <br>
<span v-if="msg.email">{{msg.email}}</span>
<label for="password">Password:</label>
<input type="text" v-model="password" required><br>
<span v-if="msg.password">{{msg.password}}</span>
<br>
<label for="twitter">Twitter Handle:</label>
<input type="text" v-model="twitter" required>
</form>
</div>
</template>

We first added the span element, which will contain the prompts we’ll create later. Then, added the msg array to store the values as the user types.

After that, copy the following code block into the script section.

<script>
export default {
name: 'Test',
data(){
return {
name: '',
password: '',
email: '',
msg: [],
twitter: ''
}
},
watch: {
email(value){
// binding this to the data value in the email input
this.email = value;
this.validateEmail(value);
}
},
methods:{
validateEmail(value){
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
this.msg['email'] = '';
} else{
this.msg['email'] = 'Invalid Email Address';
}
}
}
}
</script>

Here we created watchers for the mail and bound it to the email data. So, the watchers can execute the validate email function, which we wrote inside the methods, as changes occur in the data.

After that, run the application in the dev server. So it should behave like this:

Email Validation in Vue Form

Password validation

We want to validate that the password is are least eight characters long. If it contains fewer than eight characters, we’ll prompt the user to make it eight.

Replace the script section of the test.vue component with the code block below.

<script>
export default {
name: 'Test',
data(){
return {
name: '',
password: '',
email: '',
msg: [],
twitter: ''
}
},
watch: {
email(value){
// binding this to the data value in the email input
this.email = value;
this.validateEmail(value);
},
password(value){
this.password = value;
this.validatePassword(value);
}
},
methods:{
validateEmail(value){
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
{
this.msg['email'] = '';
} else{
this.msg['email'] = 'Invalid Email Address';
}
},
validatePassword(value){
let difference = 8 - value.length;
if (value.length<8) {
this.msg['password'] = 'Must be 8 characters! '+ difference + ' characters left' ;
} else {
this.msg['password'] = '';
}
}
}
}
</script>

Finally, save the changes in your IDE and run the application again. It should behave like this:

watchers

Conclusion with Watchers

To sum up, you should now know how to use the watch option to perform form validation in Vue. Above all, validation is crucial when building forms. Likewise the practical code illustrations in this tutorial should help you learn how to implement form validation in your Vue apps.

Want to work with web development company, including watchers in Vue ?

A web and mobile development company is the best option if you’re planning a mid-sized or large project but don’t have your own team. To clarify, the biggest advantage of a software development company is that they can take ownership of the whole project.

If you’re considering web development services, you can explore more about us – ArrowHiTech. Above all, we are proud to be one of the most well-established outsourcing companies all around the world. In addition, with over 12 years of experience, we can provide the best software development services for your eCommerce business.

So, you can check us out now: ArrowHiTech services. Also, if you want to go through our showcase, you should visit our product page here: MageSolution or our portfolio: ArrowHiTech portfolio.

ArrowHiTech services

So, if you have any questions, don’t hesitate to contact us via:

  • Email: support@arrowhitech.com
  • Phone number: +84 243 7955 813.