Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

How to check if a textbox contains a number

Written by Frinavale, May 29th, 2007
Filtering user input is extremely important for web programming.
If input is left unfiltered users can input malicious code that can cripple your website.
This article will explain how to make sure that the user only submits a number to your .NET web application.

Server Side Validation
It is strongly recommended that you check all input submitted to the server in your server side code. It is possible for users get around your client side checks and submit malicious code. Whenever a web form is submitted, you should check to make sure that all fields contain valid data to help prevent your web site from being hacked.

In this case we need to check to see if the user has entered a number into a text box called TXT_Number after clicking a button named Button1.
Code: ( text )
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.     Try
  3.         Integer.Parse(TXT_Number.Text)
  4.     Catch ex As Exception
  5.         LBL_NumberError.Text = "You have not entered a number"
  6.     End Try
  7. End Sub

Code: ( text )
  1. private void Button1_Click(object sender, EventArgs e)
  2. {
  3.     try
  4.     {
  5.         int.Parse(TXT_Number.Text);
  6.     }
  7.     catch
  8.     {
  9.         LBL_NumberError.Text = "You have not entered a number";
  10.     }
  11. }

In this code, if the text value in the TXT_Number text box was not a number then Integer.Parse() would throw an exception. The exception is then caught and an error message is displayed in the label LBL_NumberError. This is the simplest way I can think of to check if the user has entered a number.


Client Side Validation
Say we don't even want the user to be able to enter numbers into the text box. To do this we have to use a client side script.

The following JavaScript code snippet checks the key the user pressed and returns False if it was not a number.
Code: ( text )
  1. <script type="text/javascript">
  2. <!--
  3.  function NumberFilter(e)
  4.  {          /*Grabbing the unicode value of the key that was pressed*/
  5.             var unicode;
  6.     try
  7.     {   /*IE*/
  8.         unicode = e.keyCode;
  9.     }
  10.     catch(err)
  11.     {   
  12.         try
  13.         { /*Netscape, Mozilla, FireFox...*/
  14.              unicode = event.keyCode;
  15.         }
  16.         catch(error)
  17.         {  /*Other*/
  18.             unicode = e.which;
  19.          }
  20.      }
  21.     /*if the value entered is not a unicode value between 48 and 57 return false*/
  22.     if(unicode < 48 || unicode > 57)
  23.     { 
  24.       return false;
  25.     }
  26.     return true;
  27.  }
  28. -->
  29. </script>


Adding the Client Side Script to your .NET Web Application
I bet you're wondering how to use this code in your .NET web application.
Its pretty simple.

First, you copy the code into the body of your aspx page.

Or you could register the script using ClientScript.RegisterStartupScript:
Code: ( text )
  1. If Not Page Is Nothing Then
  2.          If Not ClientScript.IsStartupScriptRegistered("NumberScreening_Script") Then
  3.             Dim sb As StringBuilder = New StringBuilder
  4.             sb.Append("<script type='text/javascript'> "+ vbLF + "<!--")
  5.             sb.Append(" function NumberFilter(e)" + vbLf)
  6.             sb.Append("{" + vbLf)
  7.             sb.Append("  var unicode;" + vbLf)
  8.             sb.Append("  try" + vbLf)
  9.             sb.Append("  {" + vbLf)
  10.             sb.Append("   unicode = e.keyCode; " + vbLf)
  11.             sb.Append("  }" + vbLf)
  12.             sb.Append("  catch(err)" + vbLf)
  13.             sb.Append("  {   " + vbLf)
  14.             sb.Append("     try" + vbLf)
  15.             sb.Append("     {" + vbLf)
  16.             sb.Append("         unicode = event.keyCode;" + vbLf)
  17.             sb.Append("     }" + vbLf)
  18.             sb.Append("     catch(error)" + vbLf)
  19.             sb.Append("     { " + vbLf)
  20.             sb.Append("        unicode = e.which;" + vbLf)
  21.             sb.Append("     }" + vbLf)
  22.             sb.Append("   }" + vbLf)
  23.             sb.Append("   if(unicode < 48 || unicode > 57)" + vbLf)
  24.             sb.Append("   {  " + vbLf)
  25.             sb.Append("      return false;" + vbLf)
  26.             sb.Append("   } " + vbLf)
  27.             sb.Append("   return true;" + vbLf)
  28.             sb.Append("}" + vbLf)
  29.             sb.Append("// -->" + vbLf)
  30.             sb.Append("</script>" + vbLf)
  31.             ClientScript.RegisterStartupScript(Page.GetType, "NumberScreening_Script", sb.ToString())
  32.          End If
  33. End If


It is advisable to use this second method if you are including the script into a web user control to ensure that the script is only written to the browser once since it's possible to have multiple instances of this control on the web site.

Calling the Client Side Script
Once you have your client side script included into your aspx page, you need to call the JavaScript function that filters your text box. You do this by adding the "OnKeyPress" attribute to the text box that should hold the number value. (Recall that the text box for this example is called TXT_Number.)

To do this you simply do the following
Code: ( text )
  1. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  2.      TXT_Number.Attributes.Add("OnKeyPress", "return NumberFilter()")
  3. End Sub


Every time a key is pressed while the user enters input into your text box, the JavaScript function will check if the value was a number and returns "true" to allow that character to be entered into the text box if it is, otherwise it returns "false" and nothing is added to the text box.

Using JavaScript to ensure that the user can only enter a number is very powerful but remember that there are ways to get around this. Always be sure to include Server Side data validation to make certain that data is valid before using it.

I hope you found this helpful!
Happy Coding!

-Frinny

7 Comments Posted ( Post your comment )
Atran / June 3rd, 2007 07:02 PM
Wow, thanks for that, that was cool way.
Frinavale / June 4th, 2007 01:23 PM
Quote:
Originally Posted by Atran
Wow, thanks for that, that was cool way.

Glad it helped you :)
dotneto / August 31st, 2007 07:02 PM
Hi, I'm not an expert or something.
I think the best way to validate user input(client side) is with a regular expresion validator control, maybe use something like this for the expression.
^\d+$

if there is an expert on regex, please check if the expression works.
Frinavale / September 4th, 2007 01:13 PM
Quote:
Originally Posted by dotneto
Hi, I'm not an expert or something.
I think the best way to validate user input(client side) is with a regular expresion validator control, maybe use something like this for the expression.
^\d+$

if there is an expert on regex, please check if the expression works.


You are quite right!
But then I wouldn't have been able to give an example on how to write JavaScript to the browser using .NET ;)

-Frinny
ammoos / September 21st, 2007 06:07 AM
Thanks Frinny...

Very Nice Article....
monsoon / October 10th, 2007 11:24 AM
Thank for the code send by you is very useful to everyone
mathewgk80 / October 18th, 2007 07:18 PM
Thanks a lot.. The code yu have given is useful for me.

Thanks and regards,
Mathew

Stats:
Comments: 7