We help IT Professionals succeed at work.

How Do You Check if an ASP.NET TextBox Contains a Valid Number?

danielolorenz
on
Medium Priority
469 Views
Last Modified: 2012-05-12
Using C# how do you check if an ASP.NET textbox control contains a valid number and is not blank?

Thanks,

Dan
Comment
Watch Question

Author

Commented:
Is there a way to get it to display the error messages on a text label?
Commented:
if (TextBox1.Text == "")
        {            
            TextBox1.Text = "Textbox is blank";
        }
        else
        {
            double dbl;

            if (double.TryParse(TextBox1.Text, out dbl))
            {
                TextBox1.Text = "It is a number";
            }
            else
            {
                TextBox1.Text = "Not a number";
            }
        }
Commented:
Oops...


if (TextBox1.Text == "")
        {            
            Label1.Text = "Textbox is blank";
        }
        else
        {
            double dbl;

            if (double.TryParse(TextBox1.Text, out dbl))
            {
                Label1.Text = "It is a number";
            }
            else
            {
                Label1.Text = "Not a number";
            }
        }
Can I suggest you do it directly with form validation in asp.net and using a regex. A regex or regular expression represents a valid sequence of characters and numbers. If the input does not match the regex it is flagged with the error message you specify. Here is an example where I am validating a valid email address. To validate simple numbers is even easier.

<asp:textBox id="email" runat="server" CssClass="txtTypeStyle" Columns="40" />
      <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
        Display="None" ControlToValidate="email" ErrorMessage="You must enter an email address"></asp:RequiredFieldValidator>
           <asp:RegularExpressionValidator ID="regexpName" runat="server" Display="None"  
                                    ErrorMessage="You must enter a valid email address."
                                    ControlToValidate="email"    
                                    ValidationExpression="^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$" />
GlobaLevelProgrammer
Commented:
also:

string var_tb_1;

var_tb_1 = textbox.text;

// its in a varaible form have fun...

if var_tb_1 != ""{
  // do some code
}
else
{
// do some code
}

if var_tb_1 = "blue"{
  // do some code
}
else
{
// do some code
}
Commented:
Note that "double.TryParse" will consider "NaN" and "Infinite" as valid numbers. Not sure if you consider them a valid number.

Author

Commented:
These validators all worked great

Explore More ContentExplore courses, solutions, and other research materials related to this topic.