Veer3383
Veer3383

Reputation: 1825

VueJs Custom currency mask

My Currency mask has got some issues.

When I am typing say 10000 in the field, it formats it as expected 10,000 but the moment i shift focus to another field or press tab. The mask shifts the comma position to the left by 1. i.e. 10,000 becomes 1,0000

You can check codepan for the issue, can anyone help me with this?

https://codepen.io/veer3383/pen/BxqzLb?editors=1010#

The template:

<v-text-field @keyup="formatCurrency(initialBalance, $event)" :prefix="currency" v-model="initialBalance" label="Balance" :disabled="disabled"></v-text-field>

The method:

formatCurrency (num: any, e: any) {
    num = num + '';
    var number = num.replace(/[^\d.-]/g, '');
    var splitArray = number.split('.');
    var integer = splitArray[0];
    var mantissa = splitArray.length > 1 ? '.' + splitArray[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(integer)){
        integer = integer.replace(rgx, '$1' + ',' + '$2');
    }
    e.currentTarget.value = integer + mantissa.substring(0, 3);
},

Upvotes: 2

Views: 16056

Answers (1)

Daniel
Daniel

Reputation: 35684

You don't need a keyup AND v-model, they may end up creating a conflict. I find it's easier to use a computed value (or a watch with a formatted version).

template:

<div id="app">
  <v-app id="inspire">
    <v-form ref="form" v-model="valid" lazy-validation>
    <v-flex lg3="">
      <v-text-field :prefix="currency" v-model="initialBalanceFormatted" label="Balance" :disabled="disabled"></v-text-field>
      </v-flex>
    </v-form>
  </v-app>
</div>

script:

function formatAsCurrency (value, dec) {
  dec = dec || 0
  if (value === null) {
    return 0
  }
  return '' + value.toFixed(dec).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
}

new Vue({
  el: '#app',
  data: () => ({
    valid: true,
    disabled: false,
    currency: "£",
    initialBalance: null,
  }),

  computed: {
    initialBalanceFormatted: {
      get: function() {
        return formatAsCurrency(this.initialBalance, 0)
      },
      set: function(newValue) {
        this.initialBalance =  Number(newValue.replace(/[^0-9\.]/g, ''));
      }
    }
  }
})

It helps to turn these inputs into separate (reusable) components if you have more than one or two.

Here's an example I made a while back that uses components that can handle other types like percentage, does formatting only after blured (so your comma is not jumping) and allows to use up and down key for increment/decrement

https://codepen.io/scorch/pen/oZLLbv?editors=1010

Upvotes: 5

Related Questions