[Vuejs]-What is the best way to implement double validation in Quasar?

3👍

There are few problems with your code and Quasar validation in general

  1. Your checkboxes are not triggering validation at all. The reason is you are missing v-model on q-field. Without it, the rules are not executed for checkboxes
<q-field hide-bottom-space borderless item-aligned class="row q-pa-none" v-model="fruits_select" :rules="[fruitsRule]">
  <q-option-group :options="fruits" label="Notifications" type="checkbox" v-model="fruits_select" />
</q-field>
  1. Your custom rule also seems wrong. According to the docs:

Your custom validator will be a function which returns true if validator succeeds or String with error message if it doesn’t succeed

But your fruitsRule never retuns true. Fix:

fruitsRule () {
  return this.fruits_select.length > 0 || this.fruits_other !== "" || 'Select one or more checkboxes or fill in the others.'
}
  1. Quasar always check the rules only for the component which model has changed. So when you change the value in textbox, rules for checkboxes are not re-evaluated

Easiest thing to fix this is to use <QForm>, which has a method validate() that triggers the validation of every field in the form and execute it whenever one of the models changes:

<q-form ref="form">
  <q-field hide-bottom-space borderless item-aligned class="row q-pa-none" v-model="fruits_select" :rules="[fruitsRule]">
    <q-option-group :options="fruits" label="Notifications" type="checkbox" v-model="fruits_select" />
  </q-field>
  <q-input class="q-mt-md" v-model="fruits_other" label="Other" :rules="[fruitsRule]" />
</q-form>
watch: {
    fruits_select() {
      this.$refs.form.validate()
    },
    fruits_other() {
      this.$refs.form.validate()
    }
  },

Using QForm makes sense when you have more controls. You have only two so of course, you can leave out the QForm, place refs directly on both controls and use watchers to trigger the validation of the other control.

It is not very good solution but unfortunately the Quasar’s internal validation is pretty limited. If you forms gets little bit more complicated I would recommend using external validation library – for examle Vuelidate

Demo

UPDATE: Updated my demo so all models are grouped together to one object. This allows only use single deep watcher to trigger all validations…

Leave a comment