Categories
Vue

Vee-Validate — Validation States and Form Validation

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 use check and display validation states.

Also, we look at how to validate a whole form.

Validation State

In addition to displayingerrors , we can check the validation state of the form.

Flags

There are many validation flags available. They include:

  • valid — check if the field is valid
  • invalid — check if a field is invalid
  • changed — check if a field is changed
  • touched — check if a field ha been blurred
  • untouched — check if a field isn’t blurred
  • pristine — check if field value isn’t manipulated
  • dirty — check if field value is manipulated
  • pending — indicates if field validation in progress
  • required — check if a field is required
  • validated — check if a field is validated at least once
  • passed — check if a field has been validated and it’s valid
  • failed — check if a field has been validated and it’s invalid

They are available as slot props.

So we can use them by writing:

main.js

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

extend("required", required);
Vue.component("ValidationProvider", ValidationProvider);

Vue.config.productionTip = false;

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

App.vue

<template>
  <div id="app">
    <ValidationProvider rules="required" v-slot="{ valid }">
      <input v-model="value" type="text">
      <span>{{ valid }}</span>
    </ValidationProvider>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      value: ""
    };
  }
};
</script>

We just get valid from v-slot , and display the value of it below it.

Handling Forms

In addition to checking the form validation state, we can also check if all of a form’s values are valid before submission.

For example, we can write:

main.js

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

extend("required", required);
extend("alpha", alpha);

Vue.component("ValidationProvider", ValidationProvider);
Vue.component("ValidationObserver", ValidationObserver);

Vue.config.productionTip = false;

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

App.vue

<template>
  <div id="app">
    <ValidationObserver v-slot="{ handleSubmit }">
      <form [@submit](http://twitter.com/submit "Twitter profile for @submit").prevent="handleSubmit(onSubmit)">
        <ValidationProvider rules="required|alpha" v-slot="{ errors }">
          <input v-model="name" name="name" type="text">
          <span>{{ errors[0] }}</span>
        </ValidationProvider>
        <input type="submit" value="submit">
      </form>
    </ValidationObserver>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      name: ""
    };
  },
  methods: {
    onSubmit() {
      alert("submitted");
    }
  }
};
</script>

We imported the required and alpha rules.

Also, we imported the ValidationObserver component in addition to ValidationProvider .

We nest ValidationProvider in the ValidationObserver to watch for the validation states of all fields.

The form tag has the submit handler, it’s created by getting the handleSubmit function.

Then we pass in our own onSubmit method to it.

Now when we enter alphabetic data, then we’ll see the ‘submitted’ alert.

This means onSubmit is called.

Otherwise, onSubmit won’t be called.

If it’s not called, then at least some form values aren’t valid.

Programmatic Access with $refs

We can access the form validation state with refs.

For example, we can rewrite the example by writing the following code:

<template>
  <div id="app">
    <ValidationObserver ref="form">
      <form [@submit](http://twitter.com/submit "Twitter profile for @submit").prevent="onSubmit">
        <ValidationProvider rules="required|alpha" v-slot="{ errors }">
          <input v-model="name" name="name" type="text">
          <span>{{ errors[0] }}</span>
        </ValidationProvider>
        <input type="submit" value="submit">
      </form>
    </ValidationObserver>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      name: ""
    };
  },
  methods: {
    async onSubmit() {
      const success = await this.$refs.form.validate();
      if (!success) {
        return;
      }
      alert("submitted");
      this.$nextTick(() => {
        this.$refs.form.reset();
      });
    }
  }
};
</script>

We set the ref as the 'form' .

Our onSubmit method when we click submit on the form.

Then in onSubmit , we check for form validity by running the validate method on this.$refs.form .

It returns a promise that has the success value. It resolves to true if the form is valid.

Otherwise, it’s false .

Therefore, is success is false , we stop running onSubmit .

If the form is valid, we show a ‘submitted’ alert.

We reset the value of this.name .

And we reset the form validation state with this.$refs.form.reset(); in the next render iteration with this.$nextTick .

Conclusion

We can use Vee-Validate to check the validation state of a whole form.

To do this, we use the ValidationObserver component to watch the validation state of the form.

We can check with the built-in handleSubmit function or by assigning a ref to ValidationObserver .

Leave a Reply

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