本文介绍了用于验证 PRICE 的 RegExp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试验证价格字段:
I am trying to validate a Price field:
不允许:
- 空格
- 字母
- 负值
应该允许:
- 数字
- 逗号
- 十进制
推荐答案
RegExp 用于验证价格字段:
/^(d*([.,](?=d{3}))?d+)+((?!2)[.,]dd)?$/
演示说明:http://regex101.com/r/uG5lI0/1>
要验证的 Javascript 代码:
/^(d*([.,](?=d{3}))?d+)+((?!2)[.,]dd)?$/.test(input)
仅当格式正确时才进行验证,并在各自的位置使用点或逗号.
Will validate only if in correct format, with dots or commas in their respective places.
en_US 语言环境的国际格式 &美国国家格式:
International format for the en_US locale & US national format:
- 134.56
- 1,234.56
- 2,991,234.00
2 位小数的意大利国家格式:
Italian national format with 2 decimals:
- 134,56
- 21.234,56
- 1.234,56
- 9.321.234,56
de_DE 语言环境的国际格式:
International format for the de_DE locale:
- 134,56
- 1234,56
- 98281234,56
小数是可选的,对整数进行验证:
Decimals are optional, validation for whole amounts:
- 1234
- 1,234
- 2,991,234
- 1.234
- 9.321.234
function validatePrice(input) {
return /^(d*([.,](?=d{3}))?d+)+((?!2)[.,]dd)?$/.test(input);
}
['WRONG',
'1,234,56',
'1.234.56',
'-1993',
'918,27.63',
'122.42.24',
'1,89,2',
'',
'Intl. format & US national format',
'2.56',
'14.56',
'134.56',
'1,234.56',
'2,991,234.00',
'',
'Italian national format with 2 decimals',
'9,56',
'24,56',
'134,56',
'721.234,56',
'21.234,56',
'1.234,56',
'9.321.234,56',
'69.321.234,56',
'269.321.234,56',
'1.269.321.234,56',
'International format for the de_DE locale',
'1,56',
'14,56',
'134,56',
'1234,56',
'98281234,56',
'No cents',
'1',
'14',
'134',
'1,234',
'2,991,234',
'9',
'24',
'134',
'1.234',
'9.321.234',
'1',
'14',
'134',
'1234',
'98281234'
].forEach(function(n) {
document.getElementById('results').innerHTML += "'" + n + "' => " + validatePrice(n) + "<br>";
})
<div id="results"></div>
这篇关于用于验证 PRICE 的 RegExp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!