Using watchers for form input validation in Vue.js
Tags: vue, tutorial, webdev
Published: 2020-04-06 14:50:52

---
title: Using watchers for form input validation in Vue.js
published: true
date: 2020-03-16 13:00:43 UTC
tags: vue,tutorial,webdev
canonical_url: https://blog.logrocket.com/form-input-validation-in-vue-js-using-watchers/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/szc437cnezdzxcknno4z.png
---
**Written by [Nwose Lotanna](https://blog.logrocket.com/author/nwoselotanna/)**✏️

When building forms, it’s important to be able to monitor or control the content users enter into the form fields. This is called validation. For quality assurance, you should conduct validation on both the client and server side of your application.

To help with validation, the HTML input tag has a placeholder option. You can use this to effectively direct users to the exact information you need from them. However, placeholders aren’t enough on their own to alert users when they’ve entered invalid information. That’s why developers often write scripts to prompt the user to avoid entering invalid characters.

Vue JS enables developers to use JavaScript methods to validate form inputs within Vue components. In this walkthrough, we’ll use a Vue instance option called `watch` to implement form input validation.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Prerequisites

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 is suited for developers at all stages, including beginners. Below are a few things you should already have before going through this 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:

```jsx
node -v
```

- A code editor , such as [Visual Studio Code](https://code.visualstudio.com/)
- 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 first

```jsx
npm uninstall -g vue-cli
```

  - Then, install the new one

```jsx
npm install -g @vue/cli
```

  - Download a [Vue starter project](https://github.com/viclotana/vue-canvas)
  - Unzip the downloaded project
  - Navigate into the unzipped file and run the command below to keep all the dependencies up to date

```jsx
npm install
```

## 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.

## Using Vue devtools

Throughout this tutorial, we’ll inspect our code with [Vue devtools](https://github.com/vuejs/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. Download Vue devtools for [Chrome](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd) or [Firefox](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/).

![Vue Devtools](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/vue-devtools.png?resize=720%2C593&ssl=1)

## 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.

You should have have already downloaded the canvas project. Open the project in your IDE, go into the component folder, and replace the content of your `Test.vue` file with the code block below.

```jsx
<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>
```

This creates the form with [Vue input binding](https://blog.logrocket.com/an-imperative-guide-to-forms-in-vue-js-2/). You can see it in action in the browser using the Vue devtools extension.

![Form Input Binding in Vue](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/vue-form-input-binding.gif?resize=720%2C264&ssl=1)

## 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. 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.

```jsx
<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, and then added the `msg` array to store the values as the user types.

Copy the following code block into the script section.

```jsx
<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 a watcher for the mail and bound it to the email data so that the watcher can execute the validate email function, which we wrote inside the methods, as changes occur in the data.

Run the application in the dev server. It should behave like this:

![Email Validation in Vue Form](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/vue-form-email-validation.gif?resize=720%2C368&ssl=1)

## 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.

```jsx
<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>
```

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

![Password Validation in Vue Form](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/vue-form-password-validation.gif?resize=720%2C412&ssl=1)

You can find the complete code for this tutorial on [GitHub](https://github.com/viclotana/vue_validate).

## Conclusion

You should now know how to use the `watch` option to perform form validation in Vue. Validation is crucial when building forms, and the practical code illustrations in this tutorial should help you learn how to implement form validation in your Vue apps.

* * *
## Experience your Vue apps exactly how a user does 

Debugging Vue.js applications can be difficult, especially when there are dozens, if not hundreds of mutations during a user session. If you’re interested in monitoring and tracking Vue mutations for all of your users in production, [try LogRocket.](https://www2.logrocket.com/vue-performance-monitoring)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/t4ni6gomxqbkbxygmco0.png)

[LogRocket](https://www2.logrocket.com/vue-performance-monitoring) is like a DVR for web apps, recording literally everything that happens in your Vue apps including network requests, JavaScript errors, performance problems, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.

The LogRocket Vuex plugin logs Vuex mutations to the LogRocket console, giving you context around what led to an error, and what state the application was in when an issue occurred.

Modernize how you debug your Vue apps - [Start monitoring for free.](https://www2.logrocket.com/vue-performance-monitoring)
* * *

The post [Using watchers for form input validation in Vue.js](https://blog.logrocket.com/form-input-validation-in-vue-js-using-watchers/) appeared first on [LogRocket Blog](https://blog.logrocket.com).