Link to home
Start Free TrialLog in
Avatar of jxbma
jxbmaFlag for United States of America

asked on

Regular Expression for decimal values in an ASP:RequiredFieldValidator

Hi:

I'm not great with regular expressions, so I thought I'd do a post here.

I have an  asp:RequiredFieldValidator on an asp:TextBox.
I want to add a regular expression to validate numeric/decimal values.

So, samples which would match the regex would be:
=====================================

123
123.12
123.00
123
1234
1,234
1,234.00
1,234.56
1234456
1,234,456
1,234,456.00
1,234,456.78

Any help would be greatly appreciated.

Thanks,
JohnB
Avatar of bmatumbura
bmatumbura

Try this:
^(\d|-)?(\d|,)*\.?\d*$

Open in new window

Avatar of sybe
http://www.regexlib.com/Search.aspx?k=decimal&c=3&m=5&ps=20

Here you got a list of regular expression. You can select or customize the expression which were you want to build. So take a look at the above site you even have some expression which you can just copy into your code and you should be good to go.

Good Luck.
Note: My first post also allows negative numbers and it enforces a comma between groups of 3 digits. Use this to only allow positive numbers and make the comma between digit groups optional: ^(((\d{1,3})(,\d{3})*)|(\d+))(.\d+)?$
I agree with sybe.

You could do something like the attached.  The value of i will only matter if the parse was successful.
int i;
if( Double.TryParse(myValue.ToString(), i) )
	//i now contains the double value of myValue

Open in new window

Avatar of jxbma

ASKER

I'm going with bmatumbura.
This is client side validation.
Should easily be able to do it with the right regex.

JB
Avatar of jxbma

ASKER

bmatumbura:

This works fine except for these cases:

1,234
1,234.56
It would be a lot simpler just to use a RangeValidator with its Type attribute set correctly.
^(\d{1,3},(\d{3},)*\d{3}(\.\d{1,3})?|\d{1,3}(\.\d{3})?)$
try this
ASKER CERTIFIED SOLUTION
Avatar of jxbma
jxbma
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial