473,545 Members | 2,679 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check if a textbox contains a number

Frinavale
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).

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

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

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

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

(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
19 107876
Atran
319 Contributor
Wow, thanks for that, that was cool way.
Jun 3 '07 #2
Frinavale
9,735 Recognized Expert Moderator Expert
Wow, thanks for that, that was cool way.
Glad it helped you :)
Jun 4 '07 #3
dotneto
36 New Member
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
9,735 Recognized Expert Moderator Expert
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 New Member
Thanks Frinny...

Very Nice Article....
Sep 21 '07 #6
monsoon
1 New Member
Thank for the code send by you is very useful to everyone
Oct 10 '07 #7
mathewgk80
103 New Member
Thanks a lot.. The code yu have given is useful for me.

Thanks and regards,
Mathew
Oct 18 '07 #8
IanWright
179 New Member
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
9,735 Recognized Expert Moderator Expert
Thanks for the recommendation IanWright :)

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

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

Similar topics

7
10378
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.
5
19230
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...
1
1639
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.
3
3270
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...
5
4662
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,
1
2342
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
23
138219
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
10
4515
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.
0
7428
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7941
jinu1996
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...
1
7452
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...
0
7784
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6014
agi2029
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...
1
5354
isladogs
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...
0
5071
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1916
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 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.