最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to accepts only character values in HTML5 - Stack Overflow

programmeradmin1浏览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?

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?

Share Improve this question edited Mar 14, 2013 at 14:12 ATOzTOA 36k23 gold badges99 silver badges119 bronze badges asked Mar 14, 2013 at 14:10 PeterSPeterS 7242 gold badges16 silver badges32 bronze badges 4
  • 1 What value, might i ask, isn't made up of characters? – Timothy Groote Commented 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 Commented Mar 14, 2013 at 14:13
  • 1 @TimothyGroote I guess he means letters. – Antony Commented 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/… – Jacob Tomlinson Commented Mar 14, 2013 at 14:15
Add a comment  | 

4 Answers 4

Reset to default 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

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.

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

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]+'))">
发布评论

评论列表(0)

  1. 暂无评论