JavaScript Vue

Validate Phone Number with vee-validate

Spread the love

To validate phone numbers with vee-validate, we can use the regex rule so that we can validate any phone number format we want.

First, we install the package by running:

npm i vee-validate

Next, we register the plugin in our Vue app by writing:

import Vue from "vue";
import App from "./App.vue";
import { ValidationProvider, extend } from "vee-validate";
import { regex } from "vee-validate/dist/rules";

extend("regex", regex);

Vue.component("ValidationProvider", ValidationProvider);

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)

We used the ValidationProvider package which is used to add form validation capabilities to all components in our app.

Also, we import the regex rule from the package and register it with extend so we can use the regex rule.

Then in App.vue, we write:

  <div id="app">
    <ValidationProvider :rules="{ regex:/^[2-9]\d{2}[2-9]\d{2}\d{4}$/ }" v-slot="{ errors }">
      <input name="phone" type="text" v-model="phone">
      <p>{{ errors[0] }}</p>

export default {
  name: "App",

  data() {
    return {
      phone: ""

to add a phone input field.

We wrap the ValidationProvider around the input box. The validation rule is defined by passion in an object as the value of the rules prop.

Also, we have the errors object obtained from the ValidationProvider component so that we can display form validation errors.

The name attribute must be set since it’s used for by the form validation message.

The regex /^[2-9]\d{2}[2-9]\d{2}\d{4}$/ is the regex for a North American phone number.

Once we did that, when we type in anything other than a North American phone number, we’ll see an error message displayed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *