Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Dollar validation

Tags:

regex

I've seen several posts about validating dollar amounts with RegEx and I'm pretty close to what I need but with one issue. Here is what I have so far

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

Here is what it accomplishes:

  • Leading Trailing Space not allowed
  • Positive/Negative at beginning is optional
  • Dollar Sign is optional
  • Commas are optional but if they exist ○ need to be followed by 3 digits and preceded with 1 to 3 digits
  • Decimal Point is optional but if exists: 1) No digits are required before the decimal point 2) 1 or more digits are required after a decimal point

All these conditions are met but the issue I'm having is that if the user enters only a +, -, or $ then the expression returns true. What I'm looking for is if $+- exist they must be followed by something.

I know the issue is that a number before a decimal is optional, and the decimal section itself is also optional. But I want to allow entry of .25 w/o having to force it to be entered as 0.25.

I tried adding not end of line [^$] after the optional dollar sign \$? thinking that the +-$ couldn't be followed by end of line, but that didn't seem to work.

I appreciate any help!

-Shawn

like image 637
S. Hendricks Avatar asked Sep 01 '26 12:09

S. Hendricks


1 Answers

You need to use the following regex

  1. \d* is causing the problem, so use look ahead assertion. It confirms that there will be at least one character after the symbols
  2. You need to escape ., use \. instead else it will match any character

Regex :

^[+-]?\$?(?=.)(?:\d*|\d{1,3}(?:,\d{3})*)(?:\.[0-9]+)?$

Regex explanation here

Regular expression visualization

like image 189
Pranav C Balan Avatar answered Sep 04 '26 13:09

Pranav C Balan