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.
  1. < script type = "text/javascript" >
  2. var specialKeys = new Array();
  3. specialKeys.push(8);
  4. function IsNumeric(e)
  5. {
  6. var keyCode = e.which ? e.which : e.keyCode
  7. var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
  8. document.getElementById("error").style.display = ret ? "none" : "inline";
  9. return ret;
  10. }
  11. < /script>
ASPX Page Code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="NumericKeyPressValidation.Home" %>
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>NumericKeyValidation</title>
  6. <style type="text/css"></style>

  7. <script type="text/javascript">
  8. var specialKeys = new Array();
  9. specialKeys.push(8);
  10. function IsNumeric(e)
  11. {
  12. var keyCode = e.which ? e.which : e.keyCode
  13. var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
  14. document.getElementById("error").style.display = ret ? "none" : "inline";
  15. return ret;
  16. }
  17. </script>

  18. </head>
  19. <body>
  20. Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
  21. <span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
  22. </body>
  23. </html>
Output
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.