本文介绍了RegExp用于验证PRICE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试验证价格字段:
I am trying to validate a Price field:
不允许:
- 空格
- 字母
- 负值
应该允许:
- 数字
- 逗号
- 小数
推荐答案
RegExp用于验证价格字段:
RegExp for validating Price Fields:
/^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/
解释演示:
/^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.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
- 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
- 1234
- 1,234
- 2,991,234
- 1.234
- 9.321.234
function validatePrice(input) {
return /^(\d*([.,](?=\d{3}))?\d+)+((?!\2)[.,]\d\d)?$/.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>
这篇关于RegExp用于验证PRICE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!