鍍金池/ 問答/HTML5  HTML/ vue.js對于input輸入的內(nèi)容如何使用正則表達式進行判斷

vue.js對于input輸入的內(nèi)容如何使用正則表達式進行判斷

例如如下代碼:

<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

回答
編輯回答
瘋子范

match得到的是個數(shù)組所以報錯而且正則應該是/^[0-9]d$|(^[0-9]+.[0-9]{0,8})/,watch檢測數(shù)據(jù)是沒問題的。用computed反而會麻煩一些

2017年8月6日 09:00
編輯回答
我甘愿

為什么要寫到watch里呢,你可以寫在computed里啊,寫個filter也可以啊。

2017年8月31日 19:53
編輯回答
尐潴豬

多重方式
watch

computed: {
    value: {
        set() {
        },
        get() {
        }
     }
     }
2018年8月11日 19:09
編輯回答
旖襯

我一般是寫把正則表達式封裝成一個方法,然后在輸入數(shù)據(jù)時候?qū)斎霐?shù)據(jù)進行校驗,例如,我最近做的一個項目,對輸入銀行卡號進行格式校驗。

//驗證銀行卡賬號的方法
export function isBankNumber(str) {
    const reg = /^([1-9]{1})(\d{15}|\d{18})$/
    return reg.test(str)
}
//對input標簽輸入的數(shù)據(jù)進行校驗
if (!isBankNumber(vm.temp.bankAccount.replace(/\s+/g,""))) {
                vm.showToast = true;
                vm.toastTitle = '銀行卡號格式不正確';
                vm.toastType = 'text';
                vm.toastWidth = '200px';
                return;
  }
2017年5月2日 17:46