//原生的
<input type="tel" id="bankCard" />
document.getElementById('bankCard').addEventListener('input',function () {
formatInput(this,/\D/g,19);
},false)
//格式化 /[^0-9,X]/g 身份证 /\D/g 银行卡
function formatInput(elem,patten,len) {
var curpos = elem.selectionStart;
var old_value = elem.value;
if (elem.value.replace(patten, '').length > len) {
elem.value = paddingSpace(elem.value.replace(patten, '')
.substring(0, len));
} else {
elem.value = paddingSpace(elem.value.replace(patten, ''));
}
if (old_value[curpos - 1] == ' ') {
curpos += -1;
} else {
var old_cursor = old_value.slice(0, curpos);
var old_cursor_spaced = paddingSpace(old_cursor.replace(patten,''));
curpos += old_cursor_spaced.length - old_cursor.length;
}
setTimeout(function() {
elem.focus();
//设置光标位置
elem.setSelectionRange(curpos, curpos);
}, 0);
}
// 格式化空格
function paddingSpace(str){
// return str.replace(/....(?!$)/g,'$& ')
// return str.replace(/\s/,'').replace(/([0-9,X]{4})(?=[0-9,X])/g,"$1 ");
//银行行卡号
return str.replace(/\s/,'').replace(/([0-9]{4})(?=[0-9])/g,"$1 ");
}
//vue版
<template>
<div>
<input
ref="cardInput"
id="cardInput"
type="text"
placeholder="请输入银行卡号"
@input="formatCardNumber(/\D/g)"
v-model="driveRegisterInfo.bankAccountNo"
/>
<div>
<input type="text" id="bankCard" v-model="bankCard" />
</div>
<button @click="getModal">333</button>
</div>
</template>
<script>
export default {
data() {
return {
driveRegisterInfo: {
bankAccountNo: "",
},
bankCard:''
};
},
mounted() {
let that = this;
document.getElementById("bankCard").addEventListener(
"input",
function () {
that.formatInput(this, /\D/g, 19);
},
false
);
},
methods: {
getModal(){
console.log(" this.bankCard==", this.bankCard)
console.log(" this.bankCard==", this.driveRegisterInfo.bankAccountNo)
},
formatCardNumber(patten){
let that = this
let elem = document.getElementById('cardInput');
let curpos = elem.selectionStart;
let old_value = elem.value;
that.driveRegisterInfo.bankAccountNo =
this.paddingSpace(elem.value.replace(patten, ""));
if (old_value[curpos - 1] == " ") {
curpos += -1;
} else {
var old_cursor = old_value.slice(0, curpos);
var old_cursor_spaced = this.paddingSpace(
old_cursor.replace(patten, "")
);
curpos += old_cursor_spaced.length - old_cursor.length;
}
setTimeout(function () {
elem.focus();
elem.setSelectionRange(curpos, curpos);
}, 0);
},
formatInput(elem, patten,) {
var curpos = elem.selectionStart;
var old_value = elem.value;
elem.value = this.paddingSpace(elem.value.replace(patten, ""));
if (old_value[curpos - 1] == " ") {
curpos =curpos -1;
} else {
var old_cursor = old_value.slice(0, curpos);
var old_cursor_spaced = this.paddingSpace(
old_cursor.replace(patten, "")
);
curpos =curpos+ old_cursor_spaced.length - old_cursor.length;
}
setTimeout(function () {
elem.focus();
//设置光标位置
elem.setSelectionRange(curpos, curpos);
}, 0);
},
// 格式化空格
paddingSpace(str) {
return str.replace(/\s/,'').replace(/([0-9]{4})(?=[0-9])/g,"$1 ");
},
},
};
</script>
前端 银行卡格式化js
最新推荐文章于 2024-03-12 14:41:06 发布