Question3r
Question3r

Reputation: 3802

reset v-text-field to empty text without triggering a "must not be empty"-rule

Using Vuetify, I have a basic input text field and want to reset it after submitting. When resetting it I currently update its v-model to an empty string. Unfortunately this triggers my input rules and renders an error message.

Code example:

<div id="app">
    <v-app>
        <v-text-field v-model="text" :rules="[value => !!value || 'Required']"></v-text-field>
        <v-btn @click="text = ''">submit and reset</v-btn>
    </v-app>
</div>

new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data() {
        return {
            text: ""
        };
    }
})

Is there a way I can empty the field without triggering the rule? I mean it behaves correctly and I would expect that, but when I click on the button I want to reset the field to its initial state.

Upvotes: 2

Views: 7908

Answers (2)

Vlad Gor
Vlad Gor

Reputation: 236

If you want to reset form validation only, but not form inputs, you better call this.$refs.form.resetValidation() . Because .reset() method will clear all inputs (all values will be =null) and reset their validation errors (according to Vuetify docs).

Upvotes: 1

ellisdod
ellisdod

Reputation: 1734

If you put it within a form you can call form.reset()

<v-form
    ref="form"
    >
     <v-text-field v-model="text" :rules="[value => !!value || 'Required']"></v-text-field>
     <v-btn @click="submit">submit and reset</v-btn>
</v-form>
methods : {
  submit () {
     this.$refs.form.reset()
  }
}

the example codepen used in the docs: https://codepen.io/ellisdod/pen/jOPpzOO

https://vuetifyjs.com/en/components/forms/

Upvotes: 7

Related Questions