Home » vue » Restrict v-text-field number input to single digit

Restrict v-text-field number input to single digit

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to use a series of v-text-field components to build an SMS verification code component, as such I need to restrict the input to just a single digit.

<v-text-field
            v-for="(num, key) of code"
            :key="key"
            type="number"
            outlined
            v-model.number="num.char"
        ></v-text-field>

I’ve found other answers which suggest using props such as maxlength or even pattern but these seem to be old answers for V1 of Vuetify… I’m using the latest release of V2

I could hook up a method to the @input event to manually check but feels like there is probably a simpler solution I’m missing

Answers:

Yo can define rules in data function:

data() {
  return {
    rules: {
      counter: value => value.length <= 1 || 'Max 1 character',
    }
  }
}

and then in template

<v-text-field
  v-for="(num, key) of code"
  :key="key"
  type="number"
  outlined
  v-model.number="num.char"
  :rules="[rules.counter]"
></v-text-field>

or you can still use maxlength property