0

Is there any simple way I can use to prevent user from accepting numeric values in html textbox? I've encountered some features of HTML5 like type="email" etc...

Now is there any feature for accepting only character values?

ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
PeterS
  • 724
  • 2
  • 15
  • 31

4 Answers4

14

The pattern attribute should allow you to do this.

<input name="test" type="text" pattern="[A-Za-z]+">

Edit Feb 2023 This now has about 98% support according to can I use

Jeremy French
  • 11,707
  • 6
  • 46
  • 71
4

I would do like that with jQuery :

JQuery

$("#only-text").on('keyup', function(e) {
    var val = $(this).val();
   if (val.match(/[^a-zA-Z]/g)) {
       $(this).val(val.replace(/[^a-zA-Z]/g, ''));
   }
});

See the working fiddle.

soyuka
  • 8,839
  • 3
  • 39
  • 54
1

If you want to restrict characters that can be typed into your inputs, you will have to use some Javascript to do so, example with jQuery can be found here

With plain JS you could do something like

document.getElementById("alphaonly").onkeypress=function(e){ 
var e=window.event || e 
var keyunicode=e.charCode || e.keyCode 
return (keyunicode>=65 && keyunicode<=122 || keyunicode==8 || keyunicode==32)? true : false 
} 

where "alphaonly" is id of your input

Gatekeeper
  • 1,586
  • 3
  • 21
  • 33
0

I would do like that with Vanilla JavaScript using oninput attribute:

<input name="test" type="text" oninput="this.value=(this.value.match('[a-zA-Z]+'))">
getimad
  • 1
  • 2