How to force input to only allow Alpha Letters?

匿名 (未验证) 提交于 2019-12-03 02:42:02

问题:

using jQuery here, however unable to prevent numbers from being typed into the input field

http://codepen.io/leongaban/pen/owbjg

Input

jQuery

function alphaOnly(event) {    alert(event);    var key;    if (window.event) {     key = window.event.key;   } else if (e) {     key = e.which;   }   //var key = window.event.key || event.key;   alert(key.value);   return ((key >= 65 && key = 95 && key 

I've seen plenty of examples here on how to restrict to only Numbers, and I'm using the correct key codes for a-z and A-Z. Do you see what I'm doing wrong?

回答1:

The property event.key gave me an undefined value. Instead, I used event.keyCode:

function alphaOnly(event) {   var key = event.keyCode;   return ((key >= 65 && key 

Note that the value of 8 is for the backspace key.



回答2:

Rather than relying on key codes, which can be quite cumbersome, you can instead use regular expressions. By changing the pattern we can easily restrict the input to fit our needs. Note that this works with the keypress event and will allow the use of backspace (as in the accepted answer). It will not prevent users from pasting 'illegal' chars.



回答3:

On newer browsers, you can use:

You can use regular expressions to restrict the input fields.



回答4:

  function onlyAlphabets(e, t) {             try {                 if (window.event) {                     var charCode = window.event.keyCode;                 }                 else if (e) {                     var charCode = e.which;                 }                 else { return true; }                 if ((charCode > 64 && charCode  96 && charCode 


回答5:

Nice one-liner HTML only:

 


回答6:

   function alphaOnly(event) {   var key = event.keyCode;`enter code here`   return ((key >= 65 && key 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!