How to add custom validation which calls an API in vuetify forms?

Viewed 4315

I am trying to add custom validation to a form to test for duplicate entry. How can I do it using only vuetify validation. I want to show a inline error message if the user input is duplicate.

1 Answers

Yes you can validate the name from customer input with api call and throw error to user, if the name already exist or duplicate name found

You can use rules property in vuetify text fields, it takes an array of functions and expect true(validation true, in your case name not exists) or string(if valdation false, name exists in db)

Here is the working codepen: https://codepen.io/chansv/pen/eYYdPzQ?editors=1010

<div id="app">
  <v-app id="inspire">
      <v-form
        ref="form"
        v-model="valid"
      >
        <v-text-field
          v-model="name"
          :counter="10"
          :rules="[checkDuplicate, rules.required]"
          label="Name"
          required
        ></v-text-field>
        <v-btn @click="submitbtn">submit</v-btn>
      </v-form>
    </v-row>
  </v-app>
</div>

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    valid:true,
    name: '',
    rules: {
      required: v => !!v || 'this field is required',
    }
  }),
  methods: {
    checkDuplicate(val) {
      // write your api call and return the below statement if it already exist
      if (val == 'test') {
        return `Name "${val}" already exist`;
       } else {
         return true;
       }

    },
    submitbtn() {
      this.$refs.form.validate();
    },
  },
})
Related