Inayat Kazi
Inayat Kazi

Reputation: 143

how to allow a dot '.' in a vue.js input fields

Here I have written a code in vue.js. This code is for while user enters a number in a price field then after three digit comma "," will prompt dynamically. SO this functionality is expected and it is working fine but the issue is while we try to enter a dot '.' manually it is not allowing us enter the dot. SO in this script i want to allow the user to enter a dot '.' manually. So please help me to solve this issue.

<div id="vue">
  <input type="text" v-model="price" />
</div>
<script>
new Vue({
  el: '#vue',
  data: {
    price: 0
  },
  watch: {
    price: function(newValue) {
      const result = newValue.replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }
});
</script>

Upvotes: 3

Views: 1088

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You are replacing all non-digit characters so exclude . from that. You can use negated character class.

newValue.replace(/[^.\d]/g, "")

Final code:

  watch: {
    price: function(newValue) {
      const result = newValue.replace(/[^.\d]/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }

UPDATE : And in the other replace you have to exclude comma in decimal part for that you can use negative look-behind assertion.

.replace(/\B(?<!\.\d+)(?=(\d{3})+(?!\d))/g, ",");

Final code:

  watch: {
    price: function(newValue) {
      const result = newValue.replace(/[^.\d]/g, "")
        .replace(/\B(?<!\.\d+)(?=(\d{3})+(?!\d))/g, ",");
      Vue.nextTick(() => this.price = result);
    }
  }

Upvotes: 1

Related Questions