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
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Try
- Integer.Parse(TXT_Number.Text)
- Catch ex As Exception
- LBL_NumberError.Text = "You have not entered a number"
- End Try
- End Sub
Expand|Select|Wrap|Line Numbers
- private void Button1_Click(object sender, EventArgs e)
- {
- try
- {
- int.Parse(TXT_Number.Text);
- }
- catch
- {
- LBL_NumberError.Text = "You have not 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
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- Dim checkNumber As Integer
- If Integer.TryParse(TXT_Number.Text, checkNumber) = False Then
- LBL_NumberError.Text = "You have not entered a number"
- End If
- End Sub
Expand|Select|Wrap|Line Numbers
- private void Button1_Click(object sender, EventArgs e)
- {
- int checkNumber;
- if(int.TryParse(TXT_Number.Text.checkNumber) == false){
- LBL_NumberError.Text = "You have not 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.
(JavaScript)
Expand|Select|Wrap|Line Numbers
- <script type="text/javascript">
- <!--
- function NumberFilter(e)
- { /*Grabbing the unicode value of the key that was pressed*/
- var unicode;
- try
- { /*IE*/
- unicode = e.keyCode;
- }
- catch(err)
- {
- try
- { /*Netscape, Mozilla, FireFox...*/
- unicode = event.keyCode;
- }
- catch(error)
- { /*Other*/
- unicode = e.which;
- }
- }
- /*if the value entered is not a unicode value between 48 and 57 return false*/
- if(unicode < 48 || unicode > 57)
- {
- return false;
- }
- return true;
- }
- -->
- </script>
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
- If Page IsNot Nothing Then
- If Not ClientScript.IsStartupScriptRegistered("NumberScreening_Script") Then
- Dim sb As StringBuilder = New StringBuilder
- sb.Append("<script type='text/javascript'> "+ vbLF + "<!--")
- sb.Append(" function NumberFilter(e)" + vbLf)
- sb.Append("{" + vbLf)
- sb.Append(" var unicode;" + vbLf)
- sb.Append(" try" + vbLf)
- sb.Append(" {" + vbLf)
- sb.Append(" unicode = e.keyCode; " + vbLf)
- sb.Append(" }" + vbLf)
- sb.Append(" catch(err)" + vbLf)
- sb.Append(" { " + vbLf)
- sb.Append(" try" + vbLf)
- sb.Append(" {" + vbLf)
- sb.Append(" unicode = event.keyCode;" + vbLf)
- sb.Append(" }" + vbLf)
- sb.Append(" catch(error)" + vbLf)
- sb.Append(" { " + vbLf)
- sb.Append(" unicode = e.which;" + vbLf)
- sb.Append(" }" + vbLf)
- sb.Append(" }" + vbLf)
- sb.Append(" if(unicode < 48 || unicode > 57)" + vbLf)
- sb.Append(" { " + vbLf)
- sb.Append(" return false;" + vbLf)
- sb.Append(" } " + vbLf)
- sb.Append(" return true;" + vbLf)
- sb.Append("}" + vbLf)
- sb.Append("// -->" + vbLf)
- sb.Append("</script>" + vbLf)
- ClientScript.RegisterStartupScript(Page.GetType, "NumberScreening_Script", sb.ToString())
- End If
- End If
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
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- TXT_Number.Attributes.Add("OnKeyPress", "return NumberFilter()")
- End Sub
Expand|Select|Wrap|Line Numbers
- Protected Sub Page_Load(Object sender, System.EventArgs e)
- {
- TXT_Number.Attributes.Add("OnKeyPress", "return NumberFilter()");
- }
Expand|Select|Wrap|Line Numbers
- <asp:TextBox ID="TXT_Number" runat="Server" OnKeyPress="reutrn NumberFilter()" />
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
- <div>
- <asp:Label ID="NumberEntryPrompt" runat="server" Text="Please enter a number:"></asp:Label>
- <asp:TextBox ID="TXT_Number" runat="server" />
- <asp:RegularExpressionValidator ID="RegExValidatorForTxt_Number" runat="server"
- ControlToValidate="TXT_Number"
- Text="Please enter a number"
- EnableClientScript="true"
- ValidationExpression="^[0-9]*$">
- </asp:RegularExpressionValidator>
- <asp:Button ID="Button1" Text="Submit" OnClick="Button1_Click" runat="server" />
- <asp:Label ID="errorLabel" runat="server" />
- </div>
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
- Protected Sub ButtonClick(ByVal sender As Object,ByVal e As EventArgs)
- If (Page.IsValid) Then
- errorLabel.Text = "Page is valid."
- Else
- errorLabel.Text = "Page is not valid!!"
- End If
- End Sub
Expand|Select|Wrap|Line Numbers
- protected void Button1_Click(Object sender, EventArgs e)
- {
- if (Page.IsValid)
- {
- errorLabel.Text = "Page is valid.";
- }
- else
- {
- errorLabel.Text = "Page is not valid!!";
- }
- }
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