javascript - 正则表达式货币验证

标签 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 匹配外,它工作正常。

最佳答案

正则表达式

// 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”
    • 一个异常(exception),在“$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/>');
}

关于javascript - 正则表达式货币验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16242449/

相关文章:

javascript - d3.js transition().remove() 不工作

javascript - 动态高度和 webkit-transition

javascript - 允许用户输入时间的方法存在困难

ios - 将 String 转换为 Double,然后再转换回 String

javascript - 聚焦文本字段时视口(viewport)水平移动

javascript - 警告 : Tried to load angular more than once

c++ - C++11 中的正则表达式

python - 用于解析 SDDL 的正则表达式

c - 循环和函数 : How do I calculate how many years it takes to accumulate a given amount of money to retire?

Javascript 如何将整数格式化为货币字符串?