Search code examples
javascriptvue.jsvuelidate

Dynamic range using Vuelidate's between validator


I currently have data attribute with

data() {
  return {
    stats: {
      limit: 100,
      score: 0
    }
  }
}

then I want my validation to be between 0 to the value of limit from data attribute I'm currently using Vuelidate for validating attributes.

import { required, between } from "vuelidate/lib/validators";

validations: {
  stats: {
    score: {
      between: between(0, this.stats.limit)
    }
  }
}

But this is not currently working. I'm currently getting Cannot read property limit of undefined


Solution

  • the context of vuelidate's validators is not the component instance. But, since vuelidate passes the component context trough function context, you can replace it with a custom function.

    import { required, between } from "vuelidate/lib/validators";
    
    function customBetween(value) {
      return between(0, this.stats.limit)(value)
    }
    
    validations: {
      stats: {
        score: {
          between: customBetween
        }
      }
    }