Limit the User to Typing Only Letters Into a TextBox Using JavaScript

Every developer needs to use letter validation in input fields on the client side, in other words the client wants that 3 input fields should only have letters and no end-user can fill in a value other than letters, like numbers, special characters and so on. In that case you can use JavaScript to disable the use of unwanted keys via the "onkeypress" event.

Some input fields like Name, Father's Name and Mother's Name and so on needs this kind of validation.

Note: I am assuming that a "space" may be used for the preceding kinds of fields.

To create a sample to explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

empty website

Step 2

Add a new web form named "Default.aspx" into it.

web form

Step 3

Add a "TextBox" control for Name in the page named "Default.aspx" .

TextBox

Step 4

Write a function in JavaScript that will get the ASCII code of the key that will be pressed by the user and will return "true" if it is a letter or space otherwise "false".

  1. function ValidAlphabet() {  
  2.   
  3.     var code = (event.which) ? event.which : event.keyCode;  
  4.   
  5.     if ((code >= 65 && code <= 90) ||  
  6.         (code >= 97 && code <= 122) || (code == 32))  
  7.     { return true; }  
  8.     else  
  9.     { return false; }  
  10. }   
Note: 
  1. The ASCII codes of uper-case letters lies between 65 and 90.
  2. The ASCII codes of lower-case letters lies between 97 and 122.
  3. The ASCII code of space is 32.

function

Step 5

Now to call the function of JavaScript on the "onkeypress" event of TextBox.   

  1. <asp:TextBox ID="txtName" runat="server"   
  2.    onkeypress="return ValidAlphabet()">  
  3. </asp:TextBox>  
onkeypress

Conclusion

In this article, I have described how to limit the user to typing only letters and I hope it will be beneficial for you.

Up Next
    Ebook Download
    View all
    Learn
    View all