How to use Vuelidate minValue maxValue

Total
2
Shares

I can’t find how to check greater than 0, as minValue(0) also accepts 0, but if using minValue(1) then any decimal between 0 and 1 will be not accepted as well.

Also I don’t know why I can’t use variables from data / computed for maxValue below. It works if I use maxValue(200), but I need it to be dynamic.

validations: {
    form: {
        amount: {
            maxValue: maxValue(this.maxAmount), // Uncaught TypeError: Cannot read property 'maxAmount' of undefined
        },
    },
},
validations: {
    form: {
        amount: {
            maxValue: maxValue(maxAmount), // Uncaught ReferenceError: maxAmount is not defined
        },
    },
},

Solution

I believe in this case your validations need to be a function, instead of an object.

validations() {
  return {
    form: {
      amount: { maxValue: maxValue(this.maxValue) }
    }
  }
}

You can find a relevant example here: https://vuelidate.netlify.com/#sub-dynamic-parameters

–EDIT–

Regarding the greater than 0 value, copied from my comment:

I am not entirely sure, but it seems there’s no built in validator for this case. You can either write your own validator that will look more or less like this:

const greaterThanZero = (value) => value > 0

validations() {
  form: {
    amount: {
      maxValue: greaterThanZero
    }
  } 
}

or you can use minValue(0.00000001) as a workaround Custom validators can also take parameters, so you can write greaterThan custom validator that will take a dynamic value (relevant documentation here: https://vuelidate.netlify.com/#sub-extra-parameters)

Leave a Reply

Your email address will not be published. Required fields are marked *