Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuetify rule function - how to access component label during validation?

I would like to access the label property of a component in it's "Rules" function so I can return an (already) localized field name in the error message.

Is there any way to access the properties of the component in the rule function that's called by Vuetify for validation?

 <v-text-field
              v-model="obj.count"
              :counter="10"
              :label="this.$locale.get('WidgetCount')"
              :rules="MyRuleFunctionInMyRuleLibrary()"
              name="count"
              required
            ></v-text-field>

As can be seen in the code I have a function to localize the field label already, I don't want to re-do it twice or have to specify it twice. In "MyRuleFuctionInMyRuleLibrary" I want to validate the rule and report on it localized properly.

I know I can just pass the localized text Key in my rule function but that would create a redundancy as I would have to type it twice in the template and I also need some other properties of the control / component so I would rather pass or have access to the component itself. I already tried passing "this" to the component, e.g.:

 :rules="MyRuleFunctionInMyRuleLibrary(this, obj.count)"

However this in this case appears to be everything on the page / form, not the single component itself.

like image 778
JohnC Avatar asked Nov 23 '25 12:11

JohnC


1 Answers

Using typescript:

<v-text-field v-model="volume.sizePerInstance" :rules="sizePerInstanceRules" :label="$t('volumes.sizePerInstance') + '  (GB)'" type="number" step="0.01" required min="0" color="#0cc2aa"></v-text-field>

You have to define a getter in order to get acces to component properties:

get sizePerInstanceRules() {
  return [
    (v: number) => v && v > 0 || 'Max size must be greater than 0',
    (v: any) => v && !isNaN(v) || 'Max size must be a number',
    (v: number) => {
      return this.maxValue >= v || 'Exceeded limit';
    },
  ];
}
like image 177
Dani Andújar Avatar answered Nov 25 '25 09:11

Dani Andújar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!