dont allow typing if decimal point is already 2

64 views Asked by At

The use case is a user is allowed to input number that has decimal point less than either 2 or 1. For e.g these are the valid ones;

10.12
10.1
10.00
10

but 10.123 is invalid

I am able to do this in two different way. One using regex pattern and other by getting the position of decimal and checking how many digits are there after decimal. This way actually its working however I am facing one strange issue. The issue is when I type 10.11 and then type 2 it wont allow and if I again type 2 it will then be 10.112 but instead of typing 2 for consecutively second times If I type 3 then it wont be 10.113 rather stay in 10.11

This is how I have done

<FormulateInput
    name="height"
    type="number"
    step=".01"
    placeholder="0.0"
    v-model="height"
    :value="getHeightValue"
    :disabled="disableHeight"
    @input="updateField('height', $event)"
    min="0"
/>

updateField(field, value) {
      const numberOfDecimal = (field === 'height' || field === 'depth') ? 3 : 2
      // const nonDecimalValue = (value.indexOf(".") >= 0) ? value.substr(0, value.indexOf(".")) : value
      // const decimalValue = (value.indexOf(".") >= 0) ? value.substr(value.indexOf("."), value.length) : ''
      // if (decimalValue?.length > 3) {
      //   debugger
      //   this[field] = parseFloat(value).toFixed(2)
      // }
      this[field] = (value.indexOf(".") >= 0) ? (value.substr(0, value.indexOf(".")) + value.substr(value.indexOf("."), numberOfDecimal)) : value;
      // this[field] = +value < 0 ? 0 : value;
    },

It seems like;

when I type 1 it goes to updateField when I type .1 it again goes to updateField and value gets updated to this[field] when I type 2 it again goes to updateField and value gets updated to the state when I type 2 then it sees the decimal digit as 3 so it does not get updated to the state but value on forumlate is 1.122 so if I again type 2 then it does not see any changes so updateField does not get triggered so it shows 1.122. Instead if I type 3 or any digit other than 2 then it does not show 3 digits after decimal.

I hope I made my problem clear. Sorry if its confusing.

I am using vue-formulate for my form.

0

There are 0 answers