JavaScript Only numbers / Only Letters / No letters in TextBox

avaScript to allow only numbers

textbox numbers only

In this article I will be explaining how to prevent a user from typing Alphabet letters in the text box intended for only numbers. For example, if you want to get age of a user using text box then you may not allow user to type other than numbers.

Same things in the case where you want to get the name of user. You have to prevent the user from typing numbers and special characters in this case. The JavaScript I will be using can be used in any type of server-side language including ASP.NET.

javaScript to allow only numbers

How to use these JavaScript Functions

Just add this HTML event in your text box and Everything is done!

1
onkeypress="return lettersOnly(event)"

JavaScript Functions

To allow only Numbers [Exa: Age]

1
2
3
4
5
6
7
8
//Except only numbers for Age textbox
    function onlyNumbers(event) {
        var charCode = (event.which) ? event.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }

 

To allow only Numbers and Dots [Exa: Salary]

1
2
3
4
5
6
7
8
9
10
11
// Except only numbers and dot (.) for salary textbox
function onlyDotsandNumbers(event) {
        var charCode = (event.which) ? event.which : event.keyCode
        if (charCode == 46) {
            return true;
        }
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }

 

To allow NO Alphabets

1
2
3
4
5
6
7
8
9
// No alphabets for Emp No textbox
    function noAlphabets(event) {
        var charCode = (event.which) ? event.which : event.keyCode
        if ((charCode >= 97) && (charCode <= 122) || (charCode >= 65)
 && (charCode <= 90))
            return false;
        return true;
    };

 

To allow only Alphabets [Exa: First Name]

1
2
3
4
5
6
7
8
9
10
11
12
// Allow only Alphabets
    function lettersOnly(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
          ((evt.which) ? evt.which : 0));
        if (charCode > 31 && (charCode < 65 || charCode > 90) &&
          (charCode < 97 || charCode > 122)) {
            return false;
        }
        else
            return true;
    };

 

To allow only Alphabets and White Spaces [Exa: Name]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Allow only Alphabets and White Space for Name
    function lettersOnly(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
          ((evt.which) ? evt.which : 0));
        if (charCode == 32)
            return true;
        if (charCode > 31 && (charCode < 65 || charCode > 90) &&
          (charCode < 97 || charCode > 122)) {
            return false;
        }
        else
            return true;
    }

Read More Post