Regular expression for checking numeric values

Regular expression to validate textbox where i can enter integer / float value in asp.net

+2


source to share


6 answers


Why not use CompareValidator to make sure it's 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" />

      

+7


source


^[-+]?[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?$

      

The following will match (examples):



3.4
34.34
45345
-34
.55
-.45
-2.2
1.0e-10
45.
1.e308

      

+6


source


Try the following:

^\d*\.?\d+$

      

Edit: Fredrik MΓΆrk made an excellent suggestion to make this expression culturally aware. Create an expression string like this:

String regex = String.Format("^\d*\{0}?\d+$", 
                             CultureInfo
                             .CurrentCulture
                             .NumberFormat
                             .CurrencyDecimalSeparator);

      

+5


source


As you can see from various answers, Regexes can add unnecessary complexity. float.TryParse()

will tell you for sure if the value can be made float or not.

It also takes into account regional settings on the user's machine, which regular expressions won't (or will be ugly if they try).

I would consider using something like this instead of Regex:

bool isValid = float.TryParse(textbox1.Text);

      

+4


source


^?.? [- +] [0-9] * \ [0-9] + $

+1


source


code

^ [\ d.] + $

matches multiple dots in strings like "1.1.1"

try

^ \ d + (. \ D +)? $

instead

you should also notice that in some countries a comma is used instead of a period.

+1


source







All Articles