ASP.NET 2005 - How can I force the user to enter only numbers into a text box?


I want to have two text boxes, one is for passport number, and has to accept only numbers (no symbols, or dots or alphanumeric)

And the other one is for the name, accepts only Alphabets (no numbers, symbols etc...)

I want to implement this on key press! Any ready functions?
Who is Participating?
channa_mConnect With a Mentor Commented:
You need to use the JavaScript functions restrict the key strokes only to numeric or alphabets. You can use the following functions
    <asp:TextBox ID="txtPassportNumber" runat="server"  onkeypress="return restrictToNumeric();"></asp:TextBox>
    <asp:TextBox ID="txtName" runat="server"  onkeypress="return restrictToAlphabets();"></asp:TextBox>
function restrictToNumeric(){
    if ((event.keyCode < 48 || event.keyCode > 57 )&& event.keyCode != 46 ){
     alert("Only Numbers are allowed");
             return false;
function restrictToAlphabets(){
    if ((event.keyCode > 64 && event.keyCode < 91 ) || (event.keyCode > 96 && event.keyCode < 121 )){
             return true;
    } else{
        alert("Only Alphabets are allowed");
    return false;

Open in new window

In the TextBoxes , there is property for SkinID. Set it as per your needs.
in javascript, there are many things you can do... like the following:

       alert("Please enter only numbers for the passport!");

this will alert not to use letters, and remove the invalid character, onKeyUp...

but if someone holds the key down, you're screwed... so the best way would be to loop through all characters in the textbox, and if one is not a number, remove it, and alert the user if any non numerical numbers were found, and with this function type (loop), you can also check for any @non-wanted@ characters... like a dot, !, etc...

If you use ajax, you can use the Masked Edit Text box:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.