Vuejs replace on input

Viewed 60

I'm using VueJS (vue 2) and Vuetify I have a input type "number" that allows letter "e" and "-" (normal behaviour in HTML)

What I want is to .replace('e', '') in my input

<v-text-field
            ref="Invoice"
            v-model="invoice"
            label="Invoice Number"
            required
          ></v-text-field>

What is the best way of doing this?

2 Answers

Try computed property with getter and setter:

<v-text-field
     ref="Invoice"
     v-model="invoice"
     label="Invoice Number"
     required
 ></v-text-field>

<script>
 export default {
   data() { return { invoiceNumber: 0 } },

   computed: {
     invoice: {
       get() {
         return this.invoiceNumber
       },
       set(value) {
         this.invoiceNumber = value.replace() // your code here
       }
     }
   }
 }
</script>

In order to prevent entering specific key please use key modifier instead of computed setter:

<v-text-field 
  ref="Invoice" 
  v-model="invoice" 
  label="Invoice Number" 
  required 
  @keydown.69.prevent   // 69 is keyCode for 'E' key
></v-text-field>

This will work for Vue2. Vue3 has a little bit different rules for modifiers usage.

As per my understanding, You want to prevent the user to enter the e character in the text field. If Yes, you can achieve that by using RegEx.test() method and then prevent the character to get entered.

if (/e/.test(<input character>)) {
  event.preventDefault();
}

Live Demo :

new Vue({
  el: '#app',
  data: () => ({
    invoice: null
  }),
  methods: {
    validate: function(e) {
  let char = String.fromCharCode(e.keyCode); // Get the character
  if(/^[^e]+$/.test(char)) return true; // Match with regex 
  else e.preventDefault(); // If not match, don't add to input text
}
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify@1.2.2/dist/vuetify.min.css"/>
<div id="app">
    <v-text-field
      v-model="invoice"
      label="Invoice Number"
      v-on:keypress="validate($event)"
    />
</div>

Related