Numeric KeyPress Validation in TextBox using JavaScript

Introduction

Open Visual Studio and create 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.   
  3. <!DOCTYPE html>  
  4.   
  5. <html>  
  6. <head>  
  7.     <title>NumericKeyValidation</title>  
  8.     <style type="text/css"></style>  

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

  20. </head>  
  21. <body>  
  22.   
  23.     Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />  
  24.     <span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>  
  25.       
  26. </body>  
  27. </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. 
Ebook Download
View all
Learn
View all