Home > Enterprise >  How to make Vue js vuetify input allow only 3 digits before decimal and 2 digits after decimal
How to make Vue js vuetify input allow only 3 digits before decimal and 2 digits after decimal

Time:12-22

I need to set limit to the total input number to 3. For example, user can input 333, 123 etc. However, if they use decimal point, they will be allowed to enter 2 digits after decimal point. So, these inputs are valid:

123

123.33

Here is the code I have written so far:

isNumber (event, message) {
  // preventing multiple decimal
  if (!/\d/.test(event.key) && (event.key !== '.' || /\./.test(message))) {
    return event.preventDefault()
  }

  // limiting three numbers before decimal point and two digits after decimal point
  if (/^(\d{0,3}\.)?\d{1,2}$/.test(message)) return event.preventDefault()
 
}

But, this regex, /^(\d{0,3}\.)?\d{1,2}$/ is not working for my case

CodePen Demo

CodePudding user response:

You may consider using a number input (<input type="number">), with a max property to control the number of digits, and a small keyup handler to control the value.

document.addEventListener('keyup', handle);

function handle(evt) {
  if (evt.target.id === `num`) {
    if (evt.key === `Backspace`) { return true; }
    const [number, int] = [parseFloat(evt.target.value), parseInt(evt.target.value)];
    evt.target.value = number > evt.target.max 
      ? evt.target.max : number === int 
        ? int : number.toFixed(2);
    document.querySelector(`#value`).textContent = `current value: ${evt.target.value}`;
  }
}
<input id="num" type="number" step="0.1" max="999.99">
<div id="value"></div>

CodePudding user response:

You may use the following regex:

^\d{0,3}(?:\.\d{1,2})?$

The thing to remember is to make the fractional part, including the ., optional.

Demo

  • Related