Make Vuetify rule for number between 0 and 999 or no input

Viewed 19590

I have rule that checks if number in input is between 0 and 999, it works OK. Issue is that if I enter incorrect value like a and delete it then I still have error shown even for empty input.

It must have some simple solution, I just can't find it now.

I have left only important parts of the code.

<v-text-field 
type="number"
:rules="numberRule"/>

// Vue component
data: () => ({
numberRule: [v => (!isNaN(parseFloat(v)) && v >= 0 && v <= 999) || 'Number has to be between 0 and 999']
})
1 Answers

Above code looks fine, I've added fixes to your requirement

Working codepen: https://codepen.io/chansv/pen/ZEEeVoW?editors=1010

The rules property in vuetify text-field expect an array of boolean values or string, if boolean is true then validation passed, if it finds any string then it displays as error message

I've added fixes to the numberRule to first check if the value is no input, the it wont display any error message, then checks the number from 0-999 if passes then no error message, if not passes both the case, it displays error message

<v-text-field
 label="Regular"
 :rules="[numberRule]"
></v-text-field>

In Script:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: {
    numberRule: v  => {
      if (!v.trim()) return true;
      if (!isNaN(parseFloat(v)) && v >= 0 && v <= 999) return true;
      return 'Number has to be between 0 and 999';
    },
  }
})
Related