Categories
Vuetify

Vuetify — Form Validation

Spread the love

Vuetify is a popular UI framework for Vue apps.

In this article, we’ll look at how to work with the Vuetify framework.

Validation with Submit and Clear

We can reset a form with the this.$refs.form.reset() method.

And we can reset form validation with the this.$refs.form.resetValidation() method.

For example, we can write:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-text-field v-model="name" :counter="10" :rules="nameRules" label="Name" required></v-text-field>

          <v-text-field v-model="email" :rules="emailRules" label="E-mail" required></v-text-field>

          <v-select
            v-model="select"
            :items="items"
            :rules="[v => !!v || 'Item is required']"
            label="Item"
            required
          ></v-select>

          <v-checkbox
            v-model="checkbox"
            :rules="[v => !!v || 'You must agree']"
            label="Do you agree?"
            required
          ></v-checkbox>

          <v-btn :disabled="!valid" color="success" class="mr-4" @click="validate">Validate</v-btn>
          <v-btn color="error" class="mr-4" @click="reset">Reset Form</v-btn>
          <v-btn color="warning" @click="resetValidation">Reset Validation</v-btn>
        </v-form>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
export default {
  name: "HelloWorld",
  data: () => ({
    valid: true,
    name: "",
    nameRules: [
      (v) => !!v || "Name is required",
      (v) => (v && v.length <= 10) || "Name must be less than 10 characters",
    ],
    email: "",
    emailRules: [
      (v) => !!v || "E-mail is required",
      (v) => /.+@.+..+/.test(v) || "E-mail must be valid",
    ],
    select: null,
    items: ["Item 1", "Item 2", "Item 3", "Item 4"],
    checkbox: false,
  }),

  methods: {
    validate() {
      this.$refs.form.validate();
    },
    reset() {
      this.$refs.form.reset();
    },
    resetValidation() {
      this.$refs.form.resetValidation();
    },
  },
};
</script>

We have the rules prop with the rules on each input component.

Also, we have the rules for the name and email.

And the methods let us reset the values and validation with our app.

The validate method lets us validate form fields.

We have the reset and resetValidation methods to reset forms.

Vuelidate

We can incorporate form validation into our Vuetify form by using the Vuelidate library.

For example, we can write:

<template>
  <v-container>
    <v-row>
      <v-col col="12">
        <form>
          <v-text-field
            v-model="name"
            :error-messages="nameErrors"
            :counter="10"
            label="Name"
            required
            [@input](http://twitter.com/input "Twitter profile for @input")="$v.name.$touch()"
            [@blur](http://twitter.com/blur "Twitter profile for @blur")="$v.name.$touch()"
          ></v-text-field>
          <v-text-field
            v-model="email"
            :error-messages="emailErrors"
            label="E-mail"
            required
            [@input](http://twitter.com/input "Twitter profile for @input")="$v.email.$touch()"
            [@blur](http://twitter.com/blur "Twitter profile for @blur")="$v.email.$touch()"
          ></v-text-field>
          <v-select
            v-model="select"
            :items="items"
            :error-messages="selectErrors"
            label="Item"
            required
            [@change](http://twitter.com/change "Twitter profile for @change")="$v.select.$touch()"
            [@blur](http://twitter.com/blur "Twitter profile for @blur")="$v.select.$touch()"
          ></v-select>
          <v-checkbox
            v-model="checkbox"
            :error-messages="checkboxErrors"
            label="Do you agree?"
            required
            [@change](http://twitter.com/change "Twitter profile for @change")="$v.checkbox.$touch()"
            [@blur](http://twitter.com/blur "Twitter profile for @blur")="$v.checkbox.$touch()"
          ></v-checkbox>

<v-btn class="mr-4" [@click](http://twitter.com/click "Twitter profile for @click")="submit">submit</v-btn>
          <v-btn [@click](http://twitter.com/click "Twitter profile for @click")="clear">clear</v-btn>
        </form>
      </v-col>
    </v-row>
  </v-container>
</template>
<script>
import { validationMixin } from "vuelidate";
import { required, maxLength, email } from "vuelidate/lib/validators";

export default {
  name: "HelloWorld",
  mixins: [validationMixin],

validations: {
    name: { required, maxLength: maxLength(10) },
    email: { required, email },
    select: { required },
    checkbox: {
      checked(val) {
        return val;
      },
    },
  },

data: () => ({
    name: "",
    email: "",
    select: null,
    items: ["Item 1", "Item 2", "Item 3", "Item 4"],
    checkbox: false,
  }),

computed: {
    checkboxErrors() {
      const errors = [];
      if (!this.$v.checkbox.$dirty) return errors;
      !this.$v.checkbox.checked && errors.push("You must agree");
      return errors;
    },
    selectErrors() {
      const errors = [];
      if (!this.$v.select.$dirty) return errors;
      !this.$v.select.required && errors.push("Item is required");
      return errors;
    },
    nameErrors() {
      const errors = [];
      if (!this.$v.name.$dirty) return errors;
      !this.$v.name.maxLength &&
        errors.push("Name must be at most 10 characters long");
      !this.$v.name.required && errors.push("Name is required.");
      return errors;
    },
    emailErrors() {
      const errors = [];
      if (!this.$v.email.$dirty) return errors;
      !this.$v.email.email && errors.push("Must be valid e-mail");
      !this.$v.email.required && errors.push("E-mail is required");
      return errors;
    },
  },

  methods: {
    submit() {
      this.$v.$touch();
    },
    clear() {
      this.$v.$reset();
      this.name = "";
      this.email = "";
      this.select = null;
      this.checkbox = false;
    },
  },
};
</script>

to add the form fields.

We incorporate the validationMixin provided by Vuelidate.

And we add the validations object with the name , email , and select keywords, which have the rules.

Also, we have the computed properties with the computed error messages for each field.

We get the fields from the $v object and the keys we have in the validations property.

The return error message can be set with the error-message prop on each field.

In the methods object, we have the reset method to clear the validation.

The items are also reset.

In the submit method, we have the $touch method to trigger the validation.

Conclusion

We can add forms with validation with Vuetify and Vuelidate.

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 *