0

I have an array of objects which look like

 {
    value: "text",
    length: 50,
    image_url: textPassword,
    type: "text"
  },
  {
    value: "number_lock_3",
    length: 3,
    image_url: numberLock3,
    type: "number"
  },

In my html, I have an input

passwordType() is one of the objects above.

This simply works when the type is text.

<input 

:type="passwordType().type"
:maxlength="passwordType().length"

 />

I am trying to make maxlength for the inputs, but whenever the type is number, maxlength wont work, are there any custom methods that I could use to make max length for the input based on the passwordType().length ?

Dave
  • 1
  • 1
  • 9
  • 38

1 Answers1

4

Using pattern only works for validation

You can also try max (example below), but it will let you type any value in and enforce the max only when the / buttons are used

But the most reliable solution is likely to use an @input event listener to trim the value.

Vue.createApp({
  data: () => ({
    passwordType: {
      value: "number_lock_3",
      length: 3,
      type: "number"
    }
  }),
  methods: {
    getMax(length) {
      return parseInt(''.padStart(length, '9'))
    },
    onKeydown(target, length) {
      target.value = target.value.substr(0, length)
    }
  },
}).mount("#app");
<script src="https://unpkg.com/vue@3.2.0/dist/vue.global.prod.js"></script>
<div id="app">
  <input :type="passwordType.type" :max="getMax(passwordType.length)" /> max ( {{getMax(passwordType.length)}}) <br />
  <input :type="passwordType.type" @input="(e)=>{onKeydown(e.target, passwordType.length)}" /> @input <br />

  <input v-model="passwordType.length" type="number" /> length
</div>
Daniel
  • 34,125
  • 17
  • 102
  • 150