Vuetify表单数字输入框如何限制小数点前后的指定位数
问题原因
你新增的规则无法生效有两个核心问题:
- 校验逻辑写反:Vuetify的表单校验规则要求返回
true代表校验通过,你当前的逻辑是「小数点后位数大于2时返回true」,等于只有超位时才会判定校验通过,和需求完全相反。 - 未处理无小数点的场景:如果用户输入的是整数,调用
toString().split('.')后得到的数组只有1个元素,split('.')[1]为undefined,直接访问.length会触发JS报错,导致整条规则直接失效。
修正方案
方案1:调整原有规则逻辑
补充无小数位的兼容逻辑,修正判断条件:
priceRules: [ v => !!v || 'Price is required', v => /^\d+(\.\d+)?$/.test(v) || 'Number only', v => (v && v.toString().split('.')[0].length <= 5) || 'No more than 5 digits before the decimal point', // 修正后的小数位校验规则 v => { if (!v) return true const decimalPart = v.toString().split('.')[1] // 没有小数位直接通过,有小数位则判断长度不超过2 return !decimalPart || decimalPart.length <= 2 || 'No more than 2 digits after the decimal point' } ]
方案2:正则合并校验(更简洁)
直接用单条正则覆盖所有数值格式校验,不需要拆分字符串处理,避免边界报错:
// 正则规则:匹配1-5位整数,可选匹配小数点加1-2位小数 const priceReg = /^\d{1,5}(\.\d{1,2})?$/ priceRules: [ v => !!v || 'Price is required', v => priceReg.test(v) || 'Please enter a valid number: up to 5 digits before the decimal point, up to 2 digits after' ]
内容的提问来源于stack exchange,提问作者user1896653
相关产品推荐
相关产品推荐

