Need help on regular expression in .Net:

D

Daniel

I would like to get some help on regular expression to validate
decimal numbers. It should also match negative value, empty value.

The expression:
^(\-){0,1}([1-9]{1}[0-9]{0,8}(\,[0-9]{3})*(\.[0-9]{0,8})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,8})?|0(\.[0-9]{0,8})?|(\.[0-9]{1,8})?)$
is doing this job, but matches a single hyphen "-" also.

For example: matches -12.34 but also matches -

I need help to have this expression modified to unmatch single hyphen
sign ("-") as only letter in the input.

Thanks in Advance.
 
C

Cowboy \(Gregory A. Beamer\) [MVP]

The problem is you have made the entire rest of the expression optional with
the () around it. So - will always be true. The quickest solution is to move
the (.

^((\-){0,1}[1-9]{1}[0-9]{0,8}(\,[0-9]{3})*(\.[0-9]{0,8})?|[1-9]{1}[0-9]{0,}(
\.[0-9]{0,8})?|0(\.[0-9]{0,8})?|(\.[0-9]{1,8})?)$

Do not have the time to optimize, but you will find that this no longer
finds '-' valid.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
 
J

Jo Inferis

Daniel said:
I would like to get some help on regular expression to validate
decimal numbers. It should also match negative value, empty value.

I can't help you on the regex front (only just about to read "Mastering
Regular Expressions", I'm afraid), but for this particular case why don't
you use a compare validator and check for the Double datatype? e.g.

<asp:TextBox id="txtDoubleField" runat="server"/>
<asp:CompareValidator
ControlToValidate="txtDoubleField"
Operator="DataTypeCheck"
Type="Double"
ErrorMessage="- you must provide a valid Double Value"
Display="None"
runat="server"/>

Combine this with a RequiredFieldValidator (or not if you want to allow an
empty value) and a ValidationSummary and you have a much easier way to check
user input and give feedback (in this case at least).

This is, of course, assuming you *are* using ASP.NET and checking user
input. If not, I'm sure someone else will have an answer...
 
D

Daniel

Without the ( for rest of the expression works. I am going to use it for now!!

Thanks Tampa, Jo Inferis and Cowboy.
 
D

Daniel

Without the ( for rest of the expression works. I am going to use it for now!!

Thanks Tampa, Jo Inferis and Cowboy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top