Introduction
Open Visual Studio and create a new project and select Web template from the list and select ASP.NET Empty Web Application. Enter the name of your application and click on OK.
Right-click on the project and select Add -> Web Form and name it as Home.aspx.
Paste the following JavaScript function in the head section of the Home.aspx page.
- < script type = "text/javascript" >
- var specialKeys = new Array();
- specialKeys.push(8);
- function IsNumeric(e)
- {
- var keyCode = e.which ? e.which : e.keyCode
- var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
- document.getElementById("error").style.display = ret ? "none" : "inline";
- return ret;
- }
- < /script>
ASPX Page Code
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="NumericKeyPressValidation.Home" %>
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <title>NumericKeyValidation</title>
- <style type="text/css"></style>
- <script type="text/javascript">
- var specialKeys = new Array();
- specialKeys.push(8);
- function IsNumeric(e)
- {
- var keyCode = e.which ? e.which : e.keyCode
- var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
- document.getElementById("error").style.display = ret ? "none" : "inline";
- return ret;
- }
- </script>
- </head>
- <body>
-
- Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
- <span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
-
- </body>
- </html>
Output
No error is thrown when we enter a numeric value in the textbox and when we enter any non-numeric value in the textbox an error is thrown.