Regular expression to validate a text box where i can enter an integer / float value in asp.net
Try this:
^\d*\.?\d+$
Edit: Fredrik Mörk made and excellent suggestion to make this expression culturally-aware. Build the expression string like this:
String regex = String.Format("^\d*\{0}?\d+$",
CultureInfo
.CurrentCulture
.NumberFormat
.CurrencyDecimalSeparator);
^[-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?$
Will match the following (examples):
3.4
34.34
45345
-34
.55
-.45
-2.2
1.0e-10
45.
1.e308
the code
^[\d.]+$
matches multiple dots in strings like "1.1.1"
try
^\d+(.\d+)?$
instead
you should also note that in some countries the comma is used instead of the dot.
As you can see from the various answers, Regexes can add unneeded complexity. float.TryParse()
will tell you for certain whether the value can be made a float or not.
This also takes account of regional settings on the users' machine, which regular expressions won't (or will get ugly if they try).
I'd consider using something like this instead of a Regex:
bool isValid = float.TryParse(textbox1.Text);
Why not use a CompareValidator to verify that the value is a number?
<asp:TextBox ID="numberTextBox" runat="server" />
<asp:CompareValidator ID="validator" runat="server" ControlToValidate="numberTextBox" Operator="DataTypeCheck" Type="Double" ErrorMessage="Value must be a number" />