vue.js对于input输入的内容如何使用正则表达式进行判断

例如如下代码:

<input type="text" v-model="sellPrice">
<input type="text" v-model="buyVolume">

reg:/^[0-9]+(.[0-9]{1,8})?$/
reg1:/[0-9]d*/

watch:{

    buyPrice:function(){
       
    },
    sellPrice:function(){
        let a = this.sellPrice;
        this.sellPrice = a.match(this.reg,'');
    },
    buyVolume:function(){
        this.buyVolume = this.buyVolume.match(/[0-9]\d*/,'');
       
    },
    sellVolume:function(){
        this.sellVolume = this.sellVolume.match(/[0-9]\d*/,'');
    }
}

Price无法成功。
为什么sellVolume能成功但是会报this.sellVolume.match is not a function

阅读 10.9k
4 个回答

match得到的是个数组所以报错而且正则应该是/^[0-9]d$|(^[0-9]+.[0-9]{0,8})/,watch检测数据是没问题的。用computed反而会麻烦一些

我一般是写把正则表达式封装成一个方法,然后在输入数据时候对输入数据进行校验,例如,我最近做的一个项目,对输入银行卡号进行格式校验。

//验证银行卡账号的方法
export function isBankNumber(str) {
    const reg = /^([1-9]{1})(\d{15}|\d{18})$/
    return reg.test(str)
}
//对input标签输入的数据进行校验
if (!isBankNumber(vm.temp.bankAccount.replace(/\s+/g,""))) {
                vm.showToast = true;
                vm.toastTitle = '银行卡号格式不正确';
                vm.toastType = 'text';
                vm.toastWidth = '200px';
                return;
  }

为什么要写到watch里呢,你可以写在computed里啊,写个filter也可以啊。

多重方式
watch

computed: {
    value: {
        set() {
        },
        get() {
        }
     }
     }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题