https://stackoverflow.com/a/16242575/722367
Matches $1,234.56
, 1,234.56
, 12
, $1.21
etc
// Requires a decimal and commas
^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{1,2}$
// Allows a decimal, requires commas
(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$
// Decimal and commas optional
(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$
// Decimals required, commas optional
^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{1,2}$
// *Requires/allows X here also implies "used correctly"
(?=.*\d)
^\$?
-?
to allow negative numbers[1-9]\d{0,2}
(\d{1,3})
, but that would allow "0,123"
_ One exception, can start with 0 in the case of "$0.50" or "0.50": |0
_ These regexes assume multiple leading 0's are invalid(,\d{3})*
?
before \.
if you want to disallow numbers starting with "$."\.\d{1,2}
or (\.\d{1,2})?
respectively
_ End with $
(unescaped) to make sure there's nothing after a valid number (like $1,000.00b)To use the regex, use the string's match
method and encase the regex between two forward slashes.
// The return will either be your match or null if not found
yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);
// For just a true/false response
!!yourNumber.match(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|0)?(\.[0-9]{1,2})?$/);