[Vuejs]-Input type max length based on what function value

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

Leave a comment