Home > Net >  How to prevent a "0" as the first character when typing in input type number? allow 0 to b
How to prevent a "0" as the first character when typing in input type number? allow 0 to b

Time:08-01

//doesn't work ^[1-9][0-9]*$

export const naturalNumberFormatter = (event: any) => {
   if (!/^[1-9][0-9]*$/.test(event.key)) {
     event.preventDefault();
  }

};

CodePudding user response:

The event to check is input. Just remove all the leading 0 of the value of the element.

document.querySelector("[name=salary]").addEventListener('input', function(event) {
  while (this.value.startsWith("0")) {
    this.value = this.value.slice(1)
  }
})
<input type="number" name="salary">

CodePudding user response:

Also an example with event.preventDefault (here you need to subscribe to keypress event):

const input = document.querySelector('input');

input.addEventListener('keypress', ({ key }) => {
  if (!input.value && key === '0') {
   event.preventDefault();
  }
});
<input type="number">

  • Related