6

I need a jquery or js function to only allow enter letters and white spaces. Thanks in advance.

page:

<p:inputText onkeypress="onlyLetter(this)">

function:

function onlyLetter(input){
    $(input).keypress(function(ev) {
   var keyCode = window.event ? ev.keyCode : ev.which;
  //  code

    });
}
user2683519
  • 747
  • 5
  • 11
  • 19
  • 2
    Uh. Don't bind a keypress handler in a keypress handler. Use one or the other (preferably the non-inline form setup in `$(readyFn)`). – user2864740 Nov 08 '13 at 00:02
  • See http://stackoverflow.com/a/16833636/2864740 for ideas of what the "code" might look like. Adjust as needed. – user2864740 Nov 08 '13 at 00:03

10 Answers10

12

The following code allows only a-z, A-Z, and white space.

HTML

<input id="inputTextBox" type="text" />

jQuery

$(document).on('keypress', '#inputTextBox', function (event) {
    var regex = new RegExp("^[a-zA-Z ]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});
Pang
  • 9,564
  • 146
  • 81
  • 122
VIJAY P
  • 1,363
  • 1
  • 12
  • 14
11

Note: KeyboardEvent.which is deprecated as of Jan. 1, 2020

Just use ascii codes (decimal values) of keys/digits that you want to disable or prevent from being work. ASCII Table .

HTML :

<input id="inputTextBox" type="text" />

jQuery :

$(document).ready(function(){
    $("#inputTextBox").keydown(function(event){
        var inputValue = event.which;
        // allow letters and whitespaces only.
        if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { 
            event.preventDefault(); 
        }
    });
});

jsFiddle Demo

Community
  • 1
  • 1
Md Ashaduzzaman
  • 4,032
  • 2
  • 18
  • 34
  • Letters, not digits :) – Stephen Nov 08 '13 at 01:23
  • In this code, you can input characters like !,@,#,$,%,^,&,* etc. – Edrich Sep 15 '14 at 03:37
  • 2
    Here's my updated code above to prevent catching sysmbols(!,@,#, etc). Also backspace and enter key enabled. `if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { event.preventDefault(); }` https://jsfiddle.net/lucerosama/5x7td5bc/ – user230451 May 15 '15 at 21:24
  • 5
    This is old but I came across it today. You're cutting off lowercase y and z (121 and 122). – imukai Jan 25 '17 at 08:47
10

First off, I have little experience in jQuery and will provide a vanilla javascript example. Here it is:

document.getElementById('inputid').onkeypress=function(e){
    if(!(/[a-z ]/i.test(String.fromCharCode(e.keyCode))) {
        e.preventDefault();
        return false;
    }
}
markasoftware
  • 12,292
  • 8
  • 41
  • 69
3

Tweaking Ashad Shanto answer a bit. Notice you cant type in y and z if you use the script. You have to change the inputValue from 120 to 123. Here is the ASCII table reference: http://ee.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html Use the script below to type in all the letters, space and backspace.

<script>
    $(document).ready(function(){
        $("#inputTextBox").keypress(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.
            if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
    });

</script>
taji01
  • 2,527
  • 8
  • 36
  • 80
2

you could use this simple method, that I took from this post

<input type="text" name="fullName" onkeypress="return (event.charCode > 64 && 
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" 
placeholder="Full Name">
Jesus Quevedo
  • 71
  • 1
  • 3
1

jQuery

var letters = /^[A-Za-z ]+$/;
var city_input="";
$(document).ready(function(){
    $("#city_name").on("input", function(){
        var city_value=$(this).val();
        if(city_value==="")
        {
            city_input=city_value;
        }
        else if(city_value.match(letters)===null){
            $(this).val(city_input);
        }
        else{
            city_input=city_value;
        }
    });
});
Akash Patel
  • 156
  • 4
  • 15
0

Here is the code which you can understand easily and can modify for any character char exception.

I include the exception for BACKSPACE.

Likewise you can give the exception by including the keycode inside the statement.

var c= ((e.which>=65 && e.which<91) || (e.which==8 /**Here 8 if for the Backspace**/) || (e.which=="your key code"))

https://gist.github.com/SathishSaminathan/e3c509243ead20fcae26c87fdd6f78fd

garfbradaz
  • 3,424
  • 7
  • 43
  • 70
  • 1
    A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers/8259#8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](https://stackoverflow.com/help/deleted-answers) – Dwhitz Jul 14 '17 at 14:41
  • Okay Thanks for the suggestion – Sathish Saminathan Jul 18 '17 at 06:18
0

<!DOCTYPE html>
<html>
<head>
<script
  src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<br/>
Enter Only Alphabate: <input id="txtName" name="lname">
 
 <script>
 $('#txtName').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z \s]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
        else
        {
        e.preventDefault();
        alert('Please Enter Alphabate');
        return false;
        }
    });
 </script>
</body>
</html>
Vikas
  • 71
  • 10
0

For me, adding a space inside input tag after z worked.

<p:inputText onkeydown="return /[a-z ]/i.test(event.key)">
-2
function ValidateAlpha(evt) { 
  var keyCode = (evt.which) ? evt.which : evt.keyCode if (
    (keyCode < 65 || keyCode > 90) && 
    (keyCode < 97 || keyCode > 123) && 
    keyCode != 32 && 
    keyCode != 39
  )
John Moutafis
  • 22,254
  • 11
  • 68
  • 112
  • 2
    Please format the code properly and explain how this is different from all the other answers posted 5 years ago. – JJJ Jun 21 '17 at 07:57
  • if we are calling the function in key press event it will only allow the alpha character with ' code it will allow. – Packiyaraj Shanmugam Jun 23 '17 at 08:10