Home > Net >  Vue, vuetify: How to validate input immediately after creating, adding it
Vue, vuetify: How to validate input immediately after creating, adding it

Time:07-08

I'm trying to figure out how to validate inputs immediately after adding them:

template:

<div id="app">
    <div
        v-for="(message, index) in messages"
        :key="index"
    >
        <v-text-field
            v-model="messages[index]"
            :rules="[v => !!v || 'Error: Please enter text']"
        />
    </div>
  
    <v-btn @click="add()">Add input</v-btn>
</div>

JS:

new Vue({
    el: '#app',

    data: {
        messages: ['Hi', 'Hello'],
    },

    methods: {
        add(val) {
            this.messages.push(val);
        },
    },
});

Codepen: https://codepen.io/Zurab-D/pen/dymGaRY

What I mean is that when the button is clicked, a new input appears and there is no "Error: Please enter text" error message by default.

Can I make this message appear immediately?

CodePudding user response:

You can put your template's code, where you use v-for directive, between v-form tags:

<v-form ref="form">
  <div v-for="(message, index) in messages" :key="index">
    <v-text-field v-model="messages[index]"
      :rules="[v => !!v || 'Error: Please enter text']" />
  </div>

  <v-btn @click="add()">Add input</v-btn>
</v-form>

and then inside add() method validate form by using built-in validate() function in v-form reference

async add(val) {
  this.messages.push(val);
  await this.$nextTick(); // wait until a new text-field will be rendered
  this.$refs.form.validate(); //validate form
},

An example on CodePen is here

CodePudding user response:

To achieve this you can use this.$refs.form.validate(). Wrap your inputs inside <v-form> tag and add an attribute ref="form".

Live Demo :

new Vue({
  vuetify: new Vuetify(),
  data: {
    messages: ['Hi', 'Hello']
  },
  methods: {
    required: value => !!value || 'Please enter text',
    add(val) {
            this.messages.push(val);
            setTimeout(() => {
              this.$refs.form.validate();
            })
        }
  }
}).$mount('#app')
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css"/>
<div id="app">
  <v-app>
    <v-form ref="form">
      <div v-for="(message, index) in messages" :key="index">
        <v-text-field v-model="messages[index]" :rules="[required]"/>
      </div>
      <v-btn @click="add()">Add input</v-btn>
    </v-form>
  </v-app>
</div>

  • Related