Skip to content
Advertisement

How to restrict strings in html input type text without setting type to number

I have this line of html code.

<input type="text"  minlength="12" maxlength="12" name="phone" placeholder="eg: 254700000000" required/> 

I want it to accept only numbers.The reason I used type as text, is that I also want to use the minlength and maxlength attributes. How do I achieve this? Alternatively, how can I use input type number, and have the minlength and maxlength working?

Advertisement

Answer

You have to set a JS event handler on the change event of that input.

const input = document.getElementById("the-input");


input.addEventListener("change", (e) => {
  console.log(input.value);
  
  if (!e.target.value.match(/^d*$/)) {
    input.value = e.target.value.split('').filter(c => /d/.test(c)).join('');
  }
});
<input id="the-input" type="text"  minlength="12" maxlength="12" name="phone" placeholder="eg: 254700000000" required/>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement