I need Help for currency regex in jQuery function.
Valid:
$1,530,602.24 1,530,602.24
Invalid:
$1,666.24$ ,1,666,88, 1.6.66,6 .1555.
I tried /^\$?[0-9][0-9,]*[0-9]\.?[0-9]{0,2}$/i
; it works fine except it matches 1,6,999
.
You can simply do this. Try this. See demo. var re = /^\d+(?:[.,]\d+)*$/gm; var str = '1234\n1,234\n1.
The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.
// 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})*)|\d+)?(\.\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"|0
(,\d{3})*
?
before \.
if you want to disallow numbers starting with "$."\.\d{1,2}
or (\.\d{1,2})?
respectively$
(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})?$/);
Basic Usage Example
var tests = [ "$1,530,602.24", "1,530,602.24", "$1,666.24$", ",1,666,88,", "1.6.66,6", ".1555." ]; var regex = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/; for (i = 0; i < tests.length; i++) { console.log(tests[i] + ' // ' + regex.test(tests[i])); document.write(tests[i] + ' // ' + regex.test(tests[i]) + '<br/>'); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With