ioannis
ioannis

Reputation: 33

Regular Expression in C#

i want to validate the input of a text box so as not be empty and also to accept only decimal or integer. I have tried the following regex's: ^\S[0-9],?[0-9]$ this one allows one letter at the beginning

^\S[0-9]+,?[0-9]*$ this one althought that does not allow letters, it requires for at least 2 numbers which is not desired.

thank you very much in advance for your time.

Upvotes: 1

Views: 1244

Answers (6)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

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

Starts with a digit, then possibly . more digits. If you'd like negative numbers

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

Although easier and more useful might be Double.TryParse.

Upvotes: 5

CaffGeek
CaffGeek

Reputation: 22054

This will allow positive or negative numbers, with commas, and decimals.

However, it doesn't ensure commas are in the correct places

^-?[\d,]+\.?\d*$

passing

  • 2
  • 10
  • 10,000
  • 10,000.00
  • -10
  • -10,000
  • -10,000.00

failing

  • a123
  • asdf
  • 123a

To be honest though, regex is the wrong solution for this

Upvotes: 0

Julius A
Julius A

Reputation: 39602

^[\d]{1,99}[.]\d{1,99}

Is pretty much what you need. You can try it out here: http://www.gskinner.com/RegExr/

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85036

I'd recommend just using a compare validator...

  <asp:CompareValidator id="Compare1" 
       ControlToValidate="TextBox1" 
       Operator="DataTypeCheck"
       Type="Double"
       runat="server"/>

It's designed to do the type of thing you are talking about without messing with all the regex...

I'll admit i'm not a fan of regex (unless truly needed). Take a look at this article:

Regular Expressions: Now You Have Two Problems

Upvotes: 3

KeithS
KeithS

Reputation: 71565

"^\d+(\.\d+)?$" ought to do it. This will match a string beginning with one or more digits, then optionally a decimal point and one or more additional digits. The decimal point and fractional part are grouped so if you have one, you need the other as well, but you can have neither.

The use of \S will match any non-whitespace character at the beginning, which is probably not what you want.

Upvotes: 1

Phil
Phil

Reputation: 4224

This should work ^\d{1,}.?\d{1,}$

Upvotes: 0

Related Questions