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?

4
  • 1
    What value, might i ask, isn't made up of characters? Mar 14, 2013 at 14:13
  • Do you want to prevent user from accepting something or do you want to prevent textbox from accepting input from user? Your question is realy weird...
    – Gatekeeper
    Mar 14, 2013 at 14:13
  • 1
    @TimothyGroote I guess he means letters.
    – Antony
    Mar 14, 2013 at 14:14
  • Have a look at this question. They used a jQuery plugin to validate the boxes stackoverflow.com/questions/2476378/… Mar 14, 2013 at 14:15

4 Answers 4

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

1
  • pattern works on IE 10+, Firefox 4+, Chrome 5+, and Opera 9.6+. Not sure about mobile browsers. Mar 14, 2013 at 14:19
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.

3
  • I tried this...But how can I use this with my multiple textbox?
    – PeterS
    Mar 15, 2013 at 8:27
  • Use a class instead of an ID, for example apply it to .only-text and add the class to all your textboxes !
    – soyuka
    Mar 15, 2013 at 8:32
  • just add \s in the regex : /[^a-zA-Z\s]/
    – soyuka
    Mar 15, 2013 at 9:37
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

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]+'))">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.