Connecting Tech Pros Worldwide Forums | Help | Site Map

How to check if a textbox contains a number

Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#1   May 29 '07
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 and also demonstrate how to add JavaScript to your ASPX pages.

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.
Expand|Select|Wrap|Line Numbers
  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
  8.  
Expand|Select|Wrap|Line Numbers
  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. }
  12.  
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.
Expand|Select|Wrap|Line Numbers
  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>
  30.  
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:
Expand|Select|Wrap|Line Numbers
  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
  34.  
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
Expand|Select|Wrap|Line Numbers
  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
  4.  
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



Atran's Avatar
Needs Regular Fix
 
Join Date: May 2007
Location: Sweden
Posts: 323
#2   Jun 3 '07

re: How to check if a textbox contains a number


Wow, thanks for that, that was cool way.
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#3   Jun 4 '07

re: How to check if a textbox contains a number


Quote:

Originally Posted by Atran

Wow, thanks for that, that was cool way.

Glad it helped you :)
dotneto's Avatar
Member
 
Join Date: Feb 2007
Location: Costa Rica
Posts: 36
#4   Aug 31 '07

re: How to check if a textbox contains a number


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's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#5   Sep 4 '07

re: How to check if a textbox contains a number


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's Avatar
Member
 
Join Date: Apr 2007
Posts: 91
#6   Sep 21 '07

re: How to check if a textbox contains a number


Thanks Frinny...

Very Nice Article....
Newbie
 
Join Date: Oct 2007
Posts: 1
#7   Oct 10 '07

re: How to check if a textbox contains a number


Thank for the code send by you is very useful to everyone
Member
 
Join Date: Sep 2007
Posts: 103
#8   Oct 18 '07

re: How to check if a textbox contains a number


Thanks a lot.. The code yu have given is useful for me.

Thanks and regards,
Mathew
Expert
 
Join Date: Jan 2008
Location: York
Posts: 179
#9   Jun 15 '09

re: How to check if a textbox contains a number


I would recommend a slight change to your code...

Using the following will throw an Exception. If you are going to use this approach I would actually suggest using some of the detail from the Exception and feed this back to the user.

Expand|Select|Wrap|Line Numbers
  1. try
  2.     {
  3.         int.Parse(TXT_Number.Text);
  4.     }
  5.     catch
  6.     {
  7.         LBL_NumberError.Text = "You have not entered a number";
  8.     }
  9.  
If you are purely interested in checking if the value parses as a number it would be better to use TryParse and remove the extra error checking.

Expand|Select|Wrap|Line Numbers
  1.  
  2. int result;
  3. if(int.Parse(TXT_Number.Text, out result) == false)
  4. {
  5.    LBL_NumberError.Text = "You have not entered a number";
  6. }
  7.  
It's a little more compact, uses the TryParse for what it has been designed to do and saves a little on the expense of throwing Exceptions.
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,719
#10   Jun 15 '09

re: How to check if a textbox contains a number


Thanks for the recommendation IanWright :)

At the time that I wrote this article I wasn't aware that the Integer.TryParse() method existed.
Reply