价格验证,我这个是不是已经最严谨了,高手帮忙看看是不是可以一个正则搞定
能想到的错误的几种可能,应该没别的吧?
- 不是数字
- 小数点后超过两位
- 不能小于0
- 小数点前如果超过两位且第一位不能为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;
}
我一般会在 any-rule 或者 i-hate-regex 里面找,找到了一个类似的稍微改了一下。
/^([1-9]\d{0,}|0)(\.\d{1,2})?$/