How to validate for numbers only in textbox using Javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dhanisha K P

    #1

    How to validate for numbers only in textbox using Javascript

    In ASP.NET you can use textboxes that can enter only numbers. For this, first you have to create a javascript file.

    For creating a javascript file,
    first right click on the Project name in Solution Explorer
    Then,
    select Add New Item -> JScript File-> Ok

    If you want, you can give a name to JSCript file. Here I use the name "number.js" . After that write the following code in that file.
    Code:
    function numberonly(e)
    {
        var KeyID = (window.event) ? event.keyCode : e.which; 
        if(KeyID>=48 && KeyID<=57)
            return true;
        else
            alert("Please Enter Number Only");
            return false;
     }

    Save this file. Take the source part of the webform. Add the following code in <head> of html.
    Code:
    <head>
    <script type="text/javascript" src="number.js">
    </script>
    </head>

    Take the source aspx.cs file. Inside the Page_Load function
    write the below code.
    Code:
    TextBox1.Attributes.Add("onkeypress", "return numberonly(event);");

    Where TextBox1 is the name of the TextBox where we want to enter the data.
    Last edited by Niheel; Oct 14 '10, 12:01 PM.
Working...