I have this line of html code.
JavaScript
x
2
1
<input type="text" minlength="12" maxlength="12" name="phone" placeholder="eg: 254700000000" required/>
2
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.
JavaScript
1
10
10
1
const input = document.getElementById("the-input");
2
3
4
input.addEventListener("change", (e) => {
5
console.log(input.value);
6
7
if (!e.target.value.match(/^d*$/)) {
8
input.value = e.target.value.split('').filter(c => /d/.test(c)).join('');
9
}
10
});
JavaScript
1
1
1
<input id="the-input" type="text" minlength="12" maxlength="12" name="phone" placeholder="eg: 254700000000" required/>