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

作者站长头像
站长
· 阅读数 15

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

  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;
}
回复
1个回答
avatar
test
2024-06-19

我一般会在 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, … ]
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容