input输入框输入金额校验

2,651 阅读1分钟

<dy-input v-model="price" @input="inputChange" @blur="handleBlur"/>

js校验只能输入带两位小数的金额:

    data(){
        return {
            info:{
                source:"车煮在建行开通的协议账户",
                account:"车煮建行开通的专有电子登记簿"
            },
            price:"",
            other:""
        }
    },
    inputChange(){
            // 限制输入位数为8位
            this.price = this.price.replace( /\d{8}/,'')
            // 如果输入非数字,则替换为''
            this.price = this.price.replace(/[^\d\.]/g, '');
            // 必须保证第一个为数字而不是.     
            this.price = this.price.replace(/^\./g,'');
            // 保证只有出现一个.而没有多个.     
            this.price = this.price.replace(/\.{2,}/g,'.');
            //前两位不能是0加数字
            this.price = this.price.replace(/^0\d[0-9]*/g,'');
            // 保证.只出现一次,而不能出现两次以上     
            this.price = this.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
            // 只能输入两位小数
            this.price = this.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');

     },
     
     handleBlur(){
            if(this.price == ""){
                this.price = "0.00"
            }
     },