473,836 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check if a textbox contains a number

9,735 Recognized Expert Moderator Expert
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).


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
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. }
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.TryPars e() 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.TryPars e method:

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
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. }
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.

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>
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.Re gisterStartupSc ript:

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
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.Re gisterStartupSc ript() method. You have to register your script with the ScriptManager by calling the ScriptManager.R egisterStartupS cript() 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.Re gisterStartupSc ript() 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

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
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. }
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 RegularExpressi onValidator 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>
  11.         <asp:Button ID="Button1" Text="Submit" OnClick="Button1_Click" runat="server" />
  12.         <asp:Label ID="errorLabel" runat="server" />
  13.   </div>
Notice how the EnableClientScr ipt 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 EnableClientScr ipt 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:

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
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. }


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!

May 29 '07
19 108057
111 New Member
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.

Bharath Reddy VasiReddy
Apr 1 '10 #11
5,000 Recognized Expert Expert
Try this.
Apr 1 '10 #12
9,735 Recognized Expert Moderator Expert
I updated the article to include the TryParse example :)
Apr 27 '10 #13
9,735 Recognized Expert Moderator Expert
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
111 New Member
The article was very good and impressive...ve ry different and robust way for validation....
Apr 27 '10 #15
210 Recognized Expert New Member
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"  />
This should do it too. Regular Expression Validator validates integer input and Required Field Validator prevents from null input.
Apr 28 '10 #16
9,735 Recognized Expert Moderator Expert
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 :)

Apr 28 '10 #17
9,735 Recognized Expert Moderator Expert
I added an example of how to use a RegularExpressi onValidator 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
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
9,735 Recognized Expert Moderator Expert
Akshata Prashar, what jsCall does your code do?

Do you have any questions or problems?

Nov 25 '10 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Mike L | last post by:
I want to check the text in a text box once the user tabs out of textbox, for number only.
by: orahm | last post by:
I have 2 textboxes and one button and I don't know why my code doesn't work. All I'm trying to do is write a number 1 into the textbox with the focus. so if the user puts the cursor in textBox1 and pushes the button the 1 should go into that box. If the cursor is in the other one the 1 should go there. It seems simple but doesn't work. Can anyone give me any hints? Here is the code: private void button1_Click(object sender,...
by: Bob Lehmann | last post by:
Perhaps you should work on knowing what day it is before trying the really, really, really, really hard stuff. Bob Lehmann "Adam Honek" <AdamHonek@Webmaster2001.freeserve.co.uk> wrote in message news:e5EJ28ZVFHA.2328@TK2MSFTNGP10.phx.gbl... > Hello everyone, > > I want to check if a user has entered an IP number within a textbox.
by: NH | last post by:
How can I check the value of a textbox has no more than 2 decimal places? I already check that the value is numeric, but how do I check that it is not 0.223 or .022 etc. I only want to allow up to 2 decimal places...
by: Louna | last post by:
Hello, I need to check VAT ID Number (from IE company) to check it's valid or not in C#, how can I do this ? Some source is available ? Thank you in advanced. Regards,
by: Luzuko | last post by:
I would like to know how can i restrict textbox input in VB.net using code instead of VB.net controls. e.g If i want a user to type numbers only in a textbox(ID number textbox), how can i make sure that nothing else besides numbers are typed in the textbox
by: mathewgk80 | last post by:
Hi all, I would like to get the Javascript code to check the textbox contains only numeric values or numbers.. I am using asp.net and c#.net.. Please help me.. Regards, Mathew
by: Matthias | last post by:
Dear newsgroup. I want to write a template function which accepts either integer or floating point numbers. If a certain result is not a whole number and if the template parameter is an integer, it should return false, but it should work normally if the parameter is a float. To illustrate this, I attached a minimal example.
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.