Validating Vue.js prop for props

I have a child component with the following props declaration:

   props: {
        count: Number,
        maxNum: Number
   }

      

This is fine, but I also have maxNum

one displayed in the input field with:

<input type="text" v-model="maxNum" value="maxNum">

      

This way, even if the user types "4" in the input, Vue.js thinks it is a string, when in fact it is a valid number when parsed correctly.

I tried to do this, but it didn't work correctly on the "apple" input:

   props: {
        maxNum: {
            validator: function (v) {
                parseInt(v);
                return true;
            }
        }
   }

      

What's the prescribed way to validate props when using v-model?

+3


source to share


2 answers


Oh, so Vue.JS does provide a nice way to do this, apparently.

<input type="text" v-model.number="maxNum" value="maxNum">

      



The modifier .number

allows part of the v-bind:value

equation to v-model

treat the input value as a number.

Link to v-model.number in Vue.JS manual here .

+4


source


I see that you figured out how to solve your problem, but I will try to explain anyway what is wrong here.

Problem 1

I assume you expected it to parseInt

break the non-numbered inputs, but that is not the case. parseInt(null)

, parseInt('foo')

And parseInt([{ bar: 'Baz' }])

everything will work fine, they just return NaN

. Hence, your validator will always go to the second line and return true

, thus treating any input as valid. To fix this, you will need to run parseInt

on your input and check if it returns NaN

, so your validator would like to do it like this:

validator: function (v) {
    return !isNan(parseInt(v));
}

      



Problem 2

You are not really looking for a validator. The validator just checks the input values ​​and decides if they are valid or not, it doesn't change them in any way. In other words, the corrected validator above will not cast '13'

in 13

, it will simply prevent typing 'apple'

or undefined

. '13'

will run unchanged and you will have to manually have it later

The function you are looking for was provided as an optional feature coerce

for every component in Vue 1, but has been removed for version 2. If you ever need to do this a little harder, t covered by the solution you linked to is officially it is recommended to just use the calculated value .

+1


source







All Articles