Vuelidate: Use Prop or Computed Value in Validation

Created on 2 Dec 2016  Â·  4Comments  Â·  Source: vuelidate/vuelidate

I'm trying to validate an amount between 0 and some amount passed in as a prop.

validations: {
  amount: {
    required,
    between: between(0, this.allowedAmount)
  }
}

However, I'm getting Uncaught TypeError: Cannot read property 'allowedAmount' of undefined(…). Same error whether I try to use a prop or computed property.

Do I have to create my own validator in this case?

question

Most helpful comment

this has no meaning in your context, as you are most probably in the main module's function. You can use the technique from sameAs validator and just use the context inside validation function

validations: {
  amount: {
    required,
    between (value) {
      return between(0, this.allowedAmount)(value)
    }
  }
}

In that situation this means your vm instance, the same thing what you have in render function.

All 4 comments

this has no meaning in your context, as you are most probably in the main module's function. You can use the technique from sameAs validator and just use the context inside validation function

validations: {
  amount: {
    required,
    between (value) {
      return between(0, this.allowedAmount)(value)
    }
  }
}

In that situation this means your vm instance, the same thing what you have in render function.

That's basically what I ended up doing for a workaround. If that's the preferred way of doing it, that's fine with me.

No plan to make props and computed properties available to the built-in validators so you don't have to put it in a function?

BTW, really enjoying vuelidate so far. Went from vue-validator -> vee-validator -> vuelidate and so far it's been the easiest and most straight forward to get going.

It has nothing to do with built-in validators, those do use the vm internally too. It's just Javascript. In component definition you don't have the access to any context, as it's just an object literal defined in module scope. You need a method for that.

An example is available here. It helped me: https://monterail.github.io/vuelidate/#sub-dynamic-parameters

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ecmel picture ecmel  Â·  3Comments

araujoyuri picture araujoyuri  Â·  3Comments

jfis picture jfis  Â·  3Comments

jess8bit picture jess8bit  Â·  3Comments

hasib32 picture hasib32  Â·  3Comments