Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify - How to access data in form rule

Can I access a data element in a rule?

Here is my code running

I'm trying to flip the value of a data element on a text field rule in a Vuetify form.

The rule itself works fine, however I'm unable to access the data element, I'm getting this error:

TypeError: Cannot set property 'disabled' of undefined

Here is my code:

data: function() {
return {
  disabled: false,
  rules:{
    sellerId(value){
      if(value.length == 0){
        this.disabled = true;
        return "What are you trying to do here?";  
      }
      else{
        return true;
      }
    }
  },

What am I doing wrong?

like image 464
ToddT Avatar asked Nov 18 '18 23:11

ToddT


People also ask

How do I add validation to Vuetify?

Go to the script tag outside the template tag and write the code below: <v-text-field v-model="firstname" :rules="nameRules" label="First Name" required> </v-text-field> firstname: '', lastname: '', nameRules: [ v => !! v || 'Name is required', v => (v && v.

What is ref in Vuetify?

A ref allows us to access internal methods on a component, for example, <v-form ref="form"> . this. $refs.

What is lazy validation in Vuetify?

lazy-validation. boolean. false. If enabled, value will always be true unless there are visible validation errors. You can still call validate() to manually trigger validation.


2 Answers

rules are an array of functions, and if you need the function to be able to access data property, you can define them as component methods:

data: function () {
  return {
    disabled: false
  }
},
methods: { 
  sellerId (value) {
    if (value.length === 0) {
      this.disabled = true;
      return "What are you trying to do here?";  
    } else {
      return true;
    }
  }
}

And then in your Vuetify component:

<v-text-field :rules="[ sellerId ]"></v-text-field>
like image 71
Psidom Avatar answered Sep 26 '22 15:09

Psidom


try to define rules as computed property :

data: function() {
    return {
      disabled: false,
      ...
    }
  },
  computed: {
    sellerIdRules() {
      return [
         (v) => {
        if (value.length == 0) {
          this.disabled = true;
          return "What are you trying to do here?";
        } else {
          return true;
        } ]
      }
    }
  }
like image 30
Boussadjra Brahim Avatar answered Sep 24 '22 15:09

Boussadjra Brahim