How to use Vuelidate minValue maxValue
Asked Answered
P

1

5

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
        },
    },
},
Piling answered 29/3, 2019 at 8:39 Comment(0)
E
19

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)

Ewart answered 29/3, 2019 at 8:46 Comment(3)
It works. I didn't know there is a different between using validations as object and as function. Thank you very much.Piling
Oh, I forgot, this only solves half of my question. My first question is how to use minValue for greater than 0, can you help me about that too?Piling
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 and then 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 valueEwart

© 2022 - 2024 — McMap. All rights reserved.