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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
If you use ajax, you can use the Masked Edit Text box:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.