如何在vuetify表单数字输入中检测小数点前后的特定长度

How to detect specific number of length before and after decimal point in vuetify form number input

在输入中,我只想接受小数和浮点数。小数点前最多允许 5 位数字,小数点后最多允许 2 位数字。最初,我是这样定义我的规则的:

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'
    ]

我想添加另一个规则,如果用户在小数点后键入超过 2 位数字,则显示错误消息。添加最后一条规则后,它不起作用。

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 => (v && v.toString().split('.')[1].length > 2) || 'No more than 2 digits after the decimal point'. // this is not working
    ]

如何让它正常工作?

DEMO

试试这个:

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 => (v && v.toString().split('.').length < 2) || (v && v.toString().split('.')[1].length <= 2) || 'No more than 2 digits after the decimal point'
]

这首先检查 split 结果是否有多个元素,然后检查 .

之后的最大数字