Home > database >  How to know which rule is failing in vuetify's v-text-field?
How to know which rule is failing in vuetify's v-text-field?

Time:11-21

As explained How to know if rule is failing in vuetify's v-text-field?, I can see any rule is failing or not with the model value of <v-form>.

In addition, I'd like to know which rule is falling with multi-rule v-text-area. For example, with the following component,

<template>
  <div>
    <v-form v-model="valid">
      <v-text-field
        v-model="model"
        type="number"
        label="Fetch Frequency"
        :rules="[rules.loanMin, rules.required]" 
        min="100"
        suffix="seconds"
      ></v-text-field>
    </v-form>
  </div>
</template>

<script>
export default {
  data: function(){
    return {
      device: "",
      model: "",
      item: "",
      rules: {
        required: v => !!v || 'Required.',
        loanMin: v => (v && v >= 100) || 'minimum interval is 100 min',
      }
    }
  }
}
</script>

Are there any way to know which rule ("required" or "loanMin") is falling?

CodePudding user response:

You will need to distinguish based on the error messages inside the errorBucket:

<template>
  <div>
    <v-form v-model="valid">
      <v-text-field
        ref="text"
        v-model="model"
        type="number"
        label="Fetch Frequency"
        :rules="[rules.loanMin, rules.required]" 
        min="100"
        suffix="seconds"
      ></v-text-field>
    </v-form>
  </div>
</template>

<script>
export default 
{
  data()
  {
    return {
      textRef: null,
      device: "",
      model: "",
      item: "",
      rules: 
      {
        required: v => !!v || 'Required.',
        loanMin: v => (v && v >= 100) || 'minimum interval is 100 min',
      }
    }
  },
  computed:
  {
    failedValidation()
    {
      if (!this.textRef) return '';
      switch (this.textRef.errorBucket[0])
      {
        case 'Required.': return 'required';
        case 'minimum interval is 100 min': return 'loanMin';
        default: return '';
      }
    },
  },
  mounted()
  {
    this.textRef = this.$refs.text;
  },
}
</script>
  • Related