Adam Cresswell
Adam Cresswell

Reputation: 101

Restrict input to single digit in vuejs

I have an input in VueJS which is bound using v-model e.g.

<input type="number" v-model.number="testinput">

I want to place a restriction on this input, so that it can only be a single digit, between 1 and 6. As soon as a single digit is in the box, additional key presses should have no effect. Entering an invalid digit such as 9 should also have no effect.

I'm not sure what the best approach to this would be, do I need a directive, filter, event handler, or maybe make a new custom input component?

Upvotes: 0

Views: 2504

Answers (1)

Korgrue
Korgrue

Reputation: 3478

  1. Set the maxlength property to 1 on the input field (this will restrict to single characters).

  2. Add the proper regex to the input field using the pattern property. (This will check that the input has only 1 character, and is using numbers 1-5.

     <input type="number" maxlength="1" pattern="([12345])\w{0}" v-model.number="testinput">
    

Upvotes: 1

Related Questions