By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,913 Members | 1,379 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

How to check if a textbox contains a number

Frinavale
Expert Mod 5K+
P: 9,731
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. Upon popular demand, I have added a section that also covers how to use a validator control to check if a text box contains a number. Validator controls are pretty cool. They can be configured to work client side to prevent unnecessary postbacks to the server and they set the Page.IsValid property to false if any validation errors were detected so that you can take the appropriate action in your server code as well.

Here are the sections that are covered in this article:
  • Server Side Validation
  • Client Side Validation
  • Adding the Client Side Script to your .NET Web Application
  • Calling the Client Side Script
  • Using an ASP.NET Validator to Validate the Data


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.

The following are a few examples how how to use the Integer class to check if the TXT_Number TextBox contains a number.

The Integer.Parse() method takes a string and tries to convert it into an Integer. If it cannot convert the String into an Integer it throws an exception which you can catch. If an exception is thrown then you know that the user did not enter an Integer number (or the number is too large or too small to fit into an Integer).

Example:

(VB)
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.  
(C#)
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.  
To reiterate:in the above 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.

You could also use the Integer.TryParse() method. This method also tries to convert string into a number. It returns true or false depending on whether or not it was able to convert the text into a number instead of throwing an exception. Here's an example using the Integer.TryParse method:

(VB)
Expand|Select|Wrap|Line Numbers
  1.  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.   Dim checkNumber As Integer
  3.   If Integer.TryParse(TXT_Number.Text, checkNumber) = False Then
  4.         LBL_NumberError.Text = "You have not entered a number"
  5.     End If
  6. End Sub
  7.  
(C#)
Expand|Select|Wrap|Line Numbers
  1. private void Button1_Click(object sender, EventArgs e)
  2. {
  3.     int checkNumber;
  4.     if(int.TryParse(TXT_Number.Text.checkNumber) == false){
  5.         LBL_NumberError.Text = "You have not entered a number";
  6.     }
  7. }
  8.  
There are Parse methods for every number data type. For example there is a Double.Parse and Double.TryParse method, a Float.Parse and a Float.TryParse method etc. Use the appropriate data type to check for the number that you are expecting.

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.

(JavaScript)
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:

(VB)
Expand|Select|Wrap|Line Numbers
  1. If Page IsNot 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.

Please be aware that if you are using Ajax in your page (the UpdatePanel)you cannot use the ClientScript.RegisterStartupScript() method. You have to register your script with the ScriptManager by calling the ScriptManager.RegisterStartupScript() method instead. If you are using Ajax, please review all of the methods available to you through the ScriptManager for registering your script by checking out the ScriptManager's methods.

You could also place the JavaScript into it's own .js file and use the ClientScript.RegisterStartupScript() method or ScriptManager registration methods to register the .js file with the page.

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

(VB)
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.  
(C#)
Expand|Select|Wrap|Line Numbers
  1. Protected Sub Page_Load(Object sender, System.EventArgs e) 
  2. {
  3.      TXT_Number.Attributes.Add("OnKeyPress", "return NumberFilter()");
  4. }
  5.  
Or you could add the call directly into your ASP.NET code markup for the TextBox. Like this:

Expand|Select|Wrap|Line Numbers
  1. <asp:TextBox ID="TXT_Number" runat="Server" OnKeyPress="reutrn NumberFilter()" />
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 an ASP.NET Validator to Validate the Data

Using a Validator control, is a good way to validate user input. You can configure these controls to operate client-side which will prevent an unnecessary round trip to the server. If the user is able to get around the JavaScript validation (which is quite easy to do) in an attempt purposefully submit invalid data, you can check the Page.IsValid property in your server side to prevent any data processing that should not be done if the data is invalid. This will prevent any undesired outcome.

In our example we want to check if a TextBox contains a number. To do this you need to to check to make sure the user has entered a value into the TextBox and that this value is a number. You need to add a RegularExpressionValidator to the page and link it up to the TextBox that it's associated with:

(ASP.NET "soruce" view code)
Expand|Select|Wrap|Line Numbers
  1.  <div>
  2.         <asp:Label ID="NumberEntryPrompt" runat="server" Text="Please enter a number:"></asp:Label>
  3.         <asp:TextBox ID="TXT_Number" runat="server" />
  4.         <asp:RegularExpressionValidator ID="RegExValidatorForTxt_Number" runat="server"
  5.            ControlToValidate="TXT_Number"
  6.            Text="Please enter a number" 
  7.            EnableClientScript="true"
  8.            ValidationExpression="^[0-9]*$">
  9.         </asp:RegularExpressionValidator>
  10.  
  11.         <asp:Button ID="Button1" Text="Submit" OnClick="Button1_Click" runat="server" />
  12.         <asp:Label ID="errorLabel" runat="server" />
  13.   </div>
Notice how the EnableClientScript property is set to True?

This will execute some JavaScript that checks that the TextBox contains information that matches the regular expression provided. The regular expression in this case checks if the value starts with a number, contains 1 or many numbers, and ends with a number. If it doesn't then the "Please enter a number" message will appear and the postback to the server will not occur when you submit the page (by clicking the button).

If you set the EnableClientScript property to false, then the page will submit to the server and upon returning to the browser the "Please enter text" message will appear. In the case when the page is submitted to the server you need check to see if the Page.IsValid property is true or false in your server-side code. If it's not valid then you know there was a validation error on the page and you can take the appropriate action. In this case (validating whether or not the TextBox contains a number), the best action would be not to do any processing server-side if the page is invalid; however for example purposes we will set a Label's Text to indicate whether or not the page was valid.

For example, the following will be executed when the button is clicked:

(VB)
Expand|Select|Wrap|Line Numbers
  1. Protected Sub ButtonClick(ByVal sender As Object,ByVal e As EventArgs)
  2.     If (Page.IsValid) Then
  3.         errorLabel.Text = "Page is valid."
  4.     Else
  5.         errorLabel.Text = "Page is not valid!!"
  6.     End If
  7. End Sub
(C#)
Expand|Select|Wrap|Line Numbers
  1. protected void Button1_Click(Object sender, EventArgs e)
  2. {
  3.     if (Page.IsValid)
  4.     {
  5.         errorLabel.Text = "Page is valid.";
  6.     }
  7.     else
  8.     {
  9.         errorLabel.Text = "Page is not valid!!";
  10.     }
  11. }

Summary

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. ASP.NET Validator controls are a great way to validate user input because they can be configured to validate client side and also set the Page.IsValid property to false if something was invalid, giving you a way to check that the page is valid server-side before executing anything. I believe that a combination between the Validator controls and side validation, as discussed in this article, is the best approach to input validation.

I hope you found this helpful!
Happy Coding!

-Frinny
May 29 '07 #1
Share this Article
Share on Google+
19 Comments


Atran
100+
P: 319
Wow, thanks for that, that was cool way.
Jun 3 '07 #2

Frinavale
Expert Mod 5K+
P: 9,731
Wow, thanks for that, that was cool way.
Glad it helped you :)
Jun 4 '07 #3

dotneto
P: 36
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.
Aug 31 '07 #4

Frinavale
Expert Mod 5K+
P: 9,731
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
Sep 4 '07 #5

ammoos
100+
P: 100
Thanks Frinny...

Very Nice Article....
Sep 21 '07 #6

P: 1
Thank for the code send by you is very useful to everyone
Oct 10 '07 #7

100+
P: 103
Thanks a lot.. The code yu have given is useful for me.

Thanks and regards,
Mathew
Oct 18 '07 #8

100+
P: 179
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.
Jun 15 '09 #9

Frinavale
Expert Mod 5K+
P: 9,731
Thanks for the recommendation IanWright :)

At the time that I wrote this article I wasn't aware that the Integer.TryParse() method existed.
Jun 15 '09 #10

100+
P: 111
How to find weather the entered value in a textbox is of specific datatype.

There is a method TryParse with every datatype to check weather the value is that specific datatype or not.

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.

Some of them are listed below:
Expand|Select|Wrap|Line Numbers
  1. int.TryParse
  2. decimal.TryParse
  3. DateTime.TryParse
  4. float.TryParse
  5. bool.TryParse
Most important thing is there is not need for handling exception. Hope this will be helpful.

Thanks
Bharath Reddy VasiReddy
Apr 1 '10 #11

RedSon
Expert 5K+
P: 5,000
Try this.
Apr 1 '10 #12

Frinavale
Expert Mod 5K+
P: 9,731
I updated the article to include the TryParse example :)
Apr 27 '10 #13

Frinavale
Expert Mod 5K+
P: 9,731
Actually, RedSon, you cant' use the TypeOf() method (or the GetType() method in VB.NET) in this case because the value that is being submitted to the server is a String but you are looking to check to see if it is a valid something (int, decimal, float, DateTime ...)

The TryParse method is pretty nice because there are no exceptions thrown...which reduces the overhead involved with handling exceptions and avoids possible exception throwing exploits.
Apr 27 '10 #14

100+
P: 111
The article was very good and impressive...very different and robust way for validation....
Apr 27 '10 #15

Expert 100+
P: 210
Impressive. I would also recommend usage of regular expression validator . with validation expression as ^\d+$ along with required field validator.

Example :

Expand|Select|Wrap|Line Numbers
  1. <asp:TextBox ID="txtbox" runat="server" />                                  
  2. <asp:Button ID="btnSearch" runat="server" Text="Search" ValidationGroup="1" />
  3. <asp:RegularExpressionValidator ID="rev" runat="server" ControlToValidate="txtbox" ErrorMessage="**Invalid Entry" SetFocusOnError="true" ValidationExpression="^\d+$" ValidationGroup="1" Display="Dynamic"/>
  4. <asp:RequiredFieldValidator runat="Server" ControlToValidate="txtbox" ErrorMessage="**Required" ValidationGroup="1" Display="dynamic"  />
  5.  
  6.  
This should do it too. Regular Expression Validator validates integer input and Required Field Validator prevents from null input.
Apr 28 '10 #16

Frinavale
Expert Mod 5K+
P: 9,731
Thanks for the recommendation semomaniz.
I'll add it in the next time I update the article.

I also want to add in an example of how to register the script using the ScriptManager so that it will work during asynchronous requests to the server (via UpdatePanel).

This article was written in haste years ago when the forum was being flooded with the "how do I check if a textbox contains a number" question. Judging by the number of hits it's gotten I think it has been very helpful in providing the answer. It's only natural that I update the article with more techniques on how to accomplish this.

If you have any recommendations that you would like to see in the article let me know :)

-Frinny
Apr 28 '10 #17

Frinavale
Expert Mod 5K+
P: 9,731
I added an example of how to use a RegularExpressionValidator control as well as more information on how to add JavaScript to a page using the ScriptManager. If you notice anything wrong, let me know :)
Jun 8 '10 #18

P: n/a
Akshata Prashar
Expand|Select|Wrap|Line Numbers
  1. double checkNumber;
  2. if (double.TryParse(txtSqFeet.Text, out checkNumber) == false)
  3. {
  4.   jsCall("You have not entered a number");
  5. }
Nov 25 '10 #19

Frinavale
Expert Mod 5K+
P: 9,731
Akshata Prashar, what jsCall does your code do?

Do you have any questions or problems?

-Frinny
Nov 25 '10 #20