Categories
Vue

Getting Started with Vue Form Validation with Vee-Validate

Spread the love

Form validation is a feature that’s not built into Vue.js.

However, we still need this feature very much.

In this article, we’ll look at how to add basic form validation with the Vee-Validate library.

Getting Started

We can get started by install the package.

To install it, we run:

npm install vee-validate --save

Then we can register the ValidationProvider plugin by writing:

import Vue from "vue";
import App from "./App.vue";
import { ValidationProvider } from "vee-validate";

Vue.component("ValidationProvider", ValidationProvider);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

in main.js .

This way, we can use it throughout our app.

We can also import extend to cretye our own validation rules:

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

extend("secret", {
  validate: value => value === "secret",
  message: "wrong word"
});

Vue.component("ValidationProvider", ValidationProvider);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

value has the inputted value and we return true if it’s valid and false otherwise.

message is the form validation error message that we’ll display.

Vue.component(“ValidationProvider”, ValidationProvider);

will make the ValidationProvider component available globally.

Basic Usage

We can add the ValidationProvider component int our app by writing:

<template>
  <div>
    <ValidationProvider rules="secret" v-slot="{ errors }">
      <input v-model="email" type="text">
      <span>{{ errors[0] }}</span>
    </ValidationProvider>
  </div>
</template>
<script>
export default {
  data(){
    return {
      email: ''
    }
  }
};
</script>

If we type in ‘secret’, then we’ll see nothing.

Otherwise, we’ll see the error message ‘wrong word’ that we set earlier.

errors has the error messages returned by the validator that we have before.

Component Registration

If we just want to use the ValidationProvider component in one component, we can write:

import { ValidationProvider } from 'vee-validate';

export default {
  components: {
    ValidationProvider
  }
};

to register ValidationProvider in the component.

Rule Arguments

We can add arguments to rules.

For instance, we can write:

extend("minLength", {
  validate(value, args) {
    return value.length >= args.length;
  },
  params: ["length"],
  message: "too short"
});

We have a validate method that has the args parameter.

args can have any property specified by the params property.

Therefore, in this case, we can have the length property ion args .

To use it, we can write:

<template>
  <div>
    <ValidationProvider rules="minLength:5" v-slot="{ errors }">
      <input v-model="value" type="text">
      <span>{{ errors[0] }}</span>
    </ValidationProvider>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: ""
    };
  }
};
</script>

We have:

minLength:5

to set args.length to 5.

So we’ll get an error message if value ‘s length is less than 5.

Multiple Arguments

We can have multiple arguments in our validate method.

For example, we can write:

extend("length", {
  validate(value, { min, max }) {
    return value.length >= min && value.length <= max;
  },
  params: ["min", "max"],
  message: "too short"
});

Then we can use it by writing:

<template>
  <div>
    <ValidationProvider rules="length:5,10" v-slot="{ errors }">
      <input v-model="value" type="text">
      <span>{{ errors[0] }}</span>
    </ValidationProvider>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: ""
    };
  }
};
</script>

We restructured args into min and max in the arguments.

Then we pass in the arguments separated by a comma.

Then if we enter something that’s shorter than 5 characters or longer than 10, we’ll see an error message.

Vee-Validate will automatically pass in any number of parameters and put it in args.

But putting the property names in params will let us get the by the key instead of getting them as an array.

So we can write something like:

rules="one_of:1,2,3,4,5,6,7,8"

and args will have [1, 2, 3, 4, 5, 6, 7, 8] if we defined a validate method for the one_of rule.

Messages

We can return the message in the validation function as an alternative to setting them in message .

For instance, we can write:

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

extend("positive", value => {
  if (value >= 0) {
    return true;
  }
  return "please enter a positive number";
});
Vue.component("ValidationProvider", ValidationProvider);
Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");

Then we can write:

<template>
  <div>
    <ValidationProvider rules="positive" v-slot="{ errors }">
      <input v-model="value" type="text">
      <span>{{ errors[0] }}</span>
    </ValidationProvider>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: ""
    };
  }
};
</script>

and we’ll see the ‘please enter a positive number’ displayed if we enter anything other than a positive number.

Conclusion

Vee-Validate is an easy to use package for adding form validation capabilities to a Vue app.

It’s much easier than validating inputs with our own code.

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 *