正则表达式货币验证

时间:2013-04-26 17:54:27

标签: javascript regex currency

我需要jQuery函数中的货币正则表达式的帮助。

  • 它可选择只允许“$”符号开头一次。
  • 它允许逗号作为数字组分隔符,但不能在开头或结尾。
  • 小数点后只允许2位数字。
  • 它只允许一个小数点而不是开头或结尾。

有效:

$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

2 个答案:

答案 0 :(得分:110)

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)
  • 可能或不是以美元符号开头(我认为否定数字无效):^\$?
    • 使用-?关注以允许否定数字
  • 以1-3个数字开头:[1-9]\d{0,2}
    • 几乎可以是(\d{1,3}),但这样会允许“0,123”
    • 一个例外,在“$ 0.50”或“0.50”的情况下可以从0开始:|0
    • 这些正则表达式假设多个前导0无效
  • 以逗号分隔的任意数量的三位数字:(,\d{3})*
    • 如果您要禁止以“$。”开头的号码,请在?之前删除\.
  • 需要或允许小数(一位或两位数):分别为\.\d{1,2}(\.\d{1,2})?
  • $(未转义)结束,以确保在有效数字之后没有任何内容(例如$ 1,000.00b)

要使用正则表达式,请使用字符串的match方法并将正则表达式包含在两个正斜杠之间。

// 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/>');
}

答案 1 :(得分:-1)

这是应该为你实现这一目标的正则表达式。

开头必须是数字或$符号。 逗号可以有任意数量的数字,但必须以数字开头和结尾。 在行尾可以有一个小数点,最多两位数。

var your_input = "$1,000,000.00";
var valid_dollar_amt_regex = /^\$?[0-9][0-9,]*[0-9]\.?[0-9]{0,2}$/i;

if(valid_dollar_amt_regex.test(your_input))
    alert("Valid!");

或使用此功能

function validate_money(i) {
    var valid_dollar_amt_regex = /^\$?[0-9][0-9,]*[0-9]\.?[0-9]{0,2}$/i;
    return valid_dollar_amt_regex.test(i);
}

看到它正常工作:http://jsfiddle.net/znuJf/