价格验证,我这个是不是已经最严谨了,高手帮忙看看是不是可以一个正则搞定?

价格验证,我这个是不是已经最严谨了,高手帮忙看看是不是可以一个正则搞定
能想到的错误的几种可能,应该没别的吧?

  1. 不是数字
  2. 小数点后超过两位
  3. 不能小于0
  4. 小数点前如果超过两位且第一位不能为0
const isPrice = (price) => {
    if (typeof price === 'undefined' || typeof price === 'object' || !(/^\d+(\.\d{1,2})?$/.test(price)) || price[0] === '-') {
        return false;
    }
    price = price + '';
    const prices = price.split('.');
    if (prices.length > 2) {
        return false;
    }
    if (prices[0].length > 1 && prices[0][0] === '0') {
        return false;
    }

    return true;
}
阅读 332
2 个回答

我一般会在 any-rule 或者 i-hate-regex 里面找,找到了一个类似的稍微改了一下。

/^([1-9]\d{0,}|0)(\.\d{1,2})?$/

const reg = /^([1-9]\d{0,}|0)(\.\d{1,2})?$/

const testCases1 = [0.1, 1, 1.0, 123, 1234, 12345.67, '123', '123.45']
console.log('正确用例', testCases1.map(v => reg.test(v)))
// 正确用例 Array(8) [ true, true, true, true, true, true, true, true ]

const testCases2 = [-0.99,  -1,  0.123, '0123', '00.00', '123.45.67', '123,123', '123,123.45', {}, [], '', null]
console.log('错误用例', testCases2.map(v => reg.test(v)))
// 错误用例 Array(12) [ false, false, false, false, false, false, false, false, false, false, … ]

/^(0|[1-9]\d*)(\.\d{1,2})?$/

['1', '1.23', '32.245', '0.215', '10.214', '012.24'].forEach(item => {
    console.log(/^(0|[1-9]\d*)(\.\d{1,2})?$/.test(item))
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏