Quasar Vue Framework: Reset validated input field

5.6k Views Asked by At

The Quasar app I am working on allows to take a picture and to add some text in a input field. After successfully sending the image, dialog appears and offers 2 buttons, one "Take another piture" (and the other redirects to another page):

// text input field
<div class="row justify-center q-ma-md">
  <q-input
    v-model="post.caption"
    ref="inputCaption"
    hint="Please enter at least 4 characters."
    :rules="[required(), minLength()]"
    clearable
    label="Caption *"
    dense
    class="col col-sm-6" />
</div>

// Dialog buttons
<q-dialog v-model="savedSuccessfully">
    [...]
    <q-card-actions align="right" class="text-primary">
      <q-btn unelevated rounded color="secondary" label="Take another photo" @click="resetCanvas" />
      <q-btn unelevated rounded color="primary" label="Go to postings" @click="goToPostings" />
    </q-card-actions>

The "resetCanvas" function not only resets the image canvas, but also the input field Unfortunately upon resetValidation() – which, according to Quasar's documentation should do the job – the input field is still recognised as dirty:

resetCanvas() {
  [...]

  this.$refs.inputCaption.resetValidation()
  this.$refs.inputCaption.isDirty = false
},

I even added a this.$refs.inputCaption.isDirty = false to the reset script, but to no avail. (See screenshot)

Input field still reacts to validation rules after resetValidation()

What do I have to do to clear the input field properly upon reset?

3

There are 3 best solutions below

2
On

The only thing that worked for me was using @blur on the field and resetting to the original data.

2
On

For my side I was using Vue 3 and quasar, This is a way I used to reset form after submit:

In template use:

<q-form ref="myForm">
  <!-- Your input field -->
</q-form>

In your script tag:

<script>
import {defineComponent, ref} from "vue"

export default defineComponent({
  setup(){
   const myForm = ref(null)
   
   const onSubmit = () => {
    //Your code....
    myForm.value.reset()
   }
   return{
    myForm,
    onSubmit
   }
  }
})
</script>

0
On

According to documentation to validate quasar form on button click in a separate function you should:

  1. In the component that you are validating set lazy-rules='ondemand' so it waits for validation function to fire and ref="myForm" so that validation function knows what form you are validating
  2. Attach @submit="validate" event handler to you form
  3. Create a validation function

setup () {
  const myForm = ref(null)

  function validate () {
    myForm.value.validate().then(success => {
      if (success) {
        // yay, models are correct
      }
      else {
        // oh no, user has filled in
        // at least one invalid value
      }
    })
  }

  // to reset validations:
  function reset () {
    myForm.value.resetValidation()
  }

  return {
    myForm,
    // ...
  }
}