正则表达式货币验证 [英] Regex currency validation
本文介绍了正则表达式货币验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在jQuery函数中使用货币正则表达式的帮助。
I need Help for currency regex in jQuery function.
- 它可选择只允许$符号开头一次。
- 它允许逗号作为数字组分隔符,但不允许在开头或结尾。
- 它只允许在小数点后舍入2位数。
- 它只允许一个小数点,而不是在开头或结尾。
- It optionally allows "$" sign only one time in beginning.
- It allows comma as digital-group-separator, but not in the beginning or the end.
- It allows only 2 digits rounded after decimal point.
- It allows only one decimal point and not in the beginning or the end.
有效期:
$1,530,602.24
1,530,602.24
无效:
$1,666.24$
,1,666,88,
1.6.66,6
.1555.
我试过 / ^ \ $?[0-9] [0 -9,] * [0-9] \ [0-9] {0,2} $ / I
?;它工作正常,但它匹配 1,6,999
。
I tried /^\$?[0-9][0-9,]*[0-9]\.?[0-9]{0,2}$/i
; it works fine except it matches 1,6,999
.
推荐答案
RegEx
The RegEx
// 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"
RegEx细分
- 当可选部分过于自由时,我们需要向前看,并保证有一个号码:
(?=。* \ d)
- 可能或不是以美元符号开头(我假设为负数)无效):
^ \ $?
- 跟随
- ?
允许负数 - When the optional parts are too liberal, we need to look ahead and guarantee there's a number:
(?=.*\d)
- May or may not start with a dollar sign (I assume negatives are invalid):
^\$?
- Follow that with
-?
to allow negative numbers - 几乎可以
(\d { 1,3})
,但这将允许0,123 - 一个例外,在$ 0.50或0.50的情况下可以从0开始:
| 0
- 这些正则表达式假设多个前导0无效
- Could almost be
(\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
- 在
\。
之前删除?
如果你想禁止以$开头的数字。 - Remove
?
before\.
if you want to disallow numbers starting with "$."
要使用正则表达式,请使用字符串的
match
方法并将正则表达式包含在两个正斜杠之间。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})?$/);
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/>'); }
这篇关于正则表达式货币验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Follow that with
The RegEx Breakdown
- 跟随
查看全文