Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force input to only allow Alpha Letters?

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

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

Input

<input type="text" name="field" maxlength="8"     title="Only Letters"     value="Type Letters Only"     onkeydown="return alphaOnly(event);"     onblur="if (this.value == '') {this.value = 'Type Letters Only';}"     onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/> 

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 <= 90) || (key >= 95 && key <= 122));  } 

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?

like image 543
Leon Gaban Avatar asked Oct 22 '13 02:10

Leon Gaban


People also ask

How do I allow only alphabets in input?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

How do you restrict the input field alphabets?

To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


2 Answers

Short ONELINER:

<input onkeydown="return /[a-z]/i.test(event.key)" >

For all unicode letters try this regexp: /\p{L}/u (but ... this) - and here is working example :)

like image 66
Kamil Kiełczewski Avatar answered Sep 19 '22 01:09

Kamil Kiełczewski


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 <= 90) || key == 8); }; 

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

like image 38
hexacyanide Avatar answered Sep 20 '22 01:09

hexacyanide