正则表达式货币格式 - javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11945412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex Currency format - javascript
提问by Adam Levitt
I'm currently using the following regex to validate currency in my html input form fields:
我目前正在使用以下正则表达式来验证我的 html 输入表单字段中的货币:
/[1-9]\d*(?:\.\d{0,2})?/
Howevever, it is allowing the following value through: 13000.234.12
但是,它允许以下值通过:13000.234.12
This is not a valid value. Here are valid values that I want to allow through:
这不是有效值。以下是我希望允许通过的有效值:
VALID
有效的
125
1.25
1000.15
700.1
80.45
0.25
INVALID
无效的
130.1.4
21.......14
It feels like there should be a standard regex pattern out there for this, thoughts?
感觉应该有一个标准的正则表达式模式,想法?
Side note: I'm preventing alphanumeric characters and dollar signs via the event key listener, so they already will not be able to be entered, which should make this problem a little easier.
旁注:我正在通过事件键侦听器阻止字母数字字符和美元符号,因此它们已经无法输入,这应该会使这个问题更容易一些。
回答by Blender
Something like this should work:
这样的事情应该工作:
^(\d*\.\d{1,2}|\d+)$
It matches:
它匹配:
1.00
1
0.23
0.2
.2
It doesn't match:
它不匹配:
.
1.1.
回答by Gareth Parker
/^(\d*?)(\.\d{1,2})?$/
So it's (Start) (Any amount of numbers only, even zero), (. and then numbers only, one or two, doesn't HAVE to be there though) End
所以它是(开始)(任何数量的数字,甚至零),(。然后只有数字,一两个,虽然不必在那里)结束
回答by Mattia Peterle
I used the comma for decimal separator. Here my friends:
我使用逗号作为小数点分隔符。这里是我的朋友们:
^([0]?(,\d{1,2})?|([1-9]{1,3})?((\.\d{3})*|([1-9])*)?(,\d{1,2})?)?$