Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In one of my textbox I wanted to compare for integer entry. I used Compare validator and Range expression validator as well. In the textbox, at the beginning if I enter a space using space
key, both the validators are not throwing error. It is accepting! Please advice for possible correction in my code or is there any possibility in C# by using the value of space bar ascii code. Following is my code for Compare validator and Range expression validator.

VB
<asp:CompareValidator ID="CompareValidator1" runat="server"
            Operator="DataTypeCheck"
            Type="Integer"
            ControlToValidate="TextBox14"
            Text="Text must be an integer." ForeColor="Red"
            style="z-index: 1; left: 90px; top: 22px; position: absolute; " />




XML
<asp:RegularExpressionValidator ID="RegularExpressionValidator31"
            runat="server" ControlToValidate="TextBox14" ErrorMessage="Enter an integer"
            Font-Size="X-Small"
            style="z-index: 1; left: 90px; top: 22px; position: absolute"
            ValidationExpression="[0.00-9.00]{1,7}"></asp:RegularExpressionValidator>
Posted
Updated 1-Feb-13 17:39pm
v2

1 solution

It is perfectly fine that the validation passes with leading or trailing spaces. The same thing would be ok if you attempted to run a TryParse or Convert on a numerical string with leading and/or trailing spaces. The numerical value is still valid, it just needs to be trimmed.

[Update]
When you postback your page and you want to work with the value in the Textbox as a numerical value, you would do something like this.
C#
// In the case you want an integer value.
int value;
if( Int32.TryParse( YourTextBox.Text, out value ) == false )
{
   // If the TryParse call fails to convert the value to an integer, 
   // set a default value here.
}

// In the case you want an double value.
double value;
if( Double.TryParse( YourTextBox.Text, out value ) == false )
{
   // If the TryParse call fails to convert the value to an double, 
   // set a default value here.
}
 
Share this answer
 
v2
Comments
S.Rajendran from Coimbatore 2-Feb-13 0:06am    
Or can I use the ascii code of space bar in c#. If so how? I am not well versed with TryParse etc as you have asked to do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900