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

Introduction

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 "on keypress" event.

Some input fields like Name, Father's Name Mother's Name, and so on need 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".

Myproject

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

Default dot ASPX

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

Add a text box

Step 4

function ValidAlphabet() {
    var code = (event.which) ? event.which : event.keyCode;   
    if ((code >= 65 && code <= 90) || 
        (code >= 97 && code <= 122) || (code == 32)) 
    {
        return true;
    } 
    else 
    {
        return false;
    }
}

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".

Note

The ASCII codes of upper-case letters lie between 65 and 90.

The ASCII codes of lower-case letters lie between 97 and 122.

The ASCII code of space is 32.

ASCII code

Step 5.

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

Now call the function of JavaScript on the "on keypress" event of TextBox.

Call the function of javascript

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.