在react开发中需要对手机号码进行格式化操作334(133 3333 3333)在这里总结一下
//手机号码分割
fromvalue(mobile) {
let value = mobile.replace(/\s+/g,'');
let valueLen = value.length;
console.log(valueLen);
if (valueLen > 3 && valueLen < 8) {
value = `${value.substr(0, 3)} ${value.substr(3)}`;
} else if (valueLen >= 8) {
value = `${value.substr(0, 3)} ${value.substr(3, 4)} ${value.substr(7)}`;
}
return value;
}
//身份证号码分割
cardValue(cardNum) {
let idCard = cardNum.replace(/\s+/g, '');
let idCardLen = idCard.length;
if (idCardLen > 3 && idCardLen < 7) {
idCard = `${idCard.substr(0, 3)} ${idCard.substr(3)}`;
} else if (idCardLen >= 7 && idCardLen < 11) {
idCard = `${idCard.substr(0, 3)} ${idCard.substr(3, 3)} ${idCard.substr(6)}`;
} else if (idCardLen >= 11 && idCardLen < 15) {
idCard = `${idCard.substr(0, 3)} ${idCard.substr(3, 3)} ${idCard.substr(6, 4)} ${idCard.substr(10)}`;
} else if (idCardLen >= 15) {
idCard = `${idCard.substr(0, 3)} ${idCard.substr(3, 3)} ${idCard.substr(6, 4)} ${idCard.substr(10, 4)} ${idCard.substr(14)}`;
}
return idCard;
}
上述代码存在的问题和解决办法
1.input 设置type属性
2.代码分割在大多浏览器都支持,在支付宝小程序中当type='tel'或者type='text'发现分割光标错误
3.这样写时输入数字按要求空格时当从中间删除某一位时发现光标回到最后
解决光标错位:在input中的 onChange={e => this.handleValue(e)}设置光标位置
handleValue(e) {
console.log();
let id=e.target.id;
let number = '';
if (this.params['type'] === 'phone') {
number = this.fromvalue(e.target.value);
} else {
number = this.cardValue(e.target.value);
}
this.setState({
[e.target.name]: number,
},()=>{
var inpObj = document.getElementById(id);
setTimeout(function(){
console.log('test');
inpObj.setSelectionRange(number.length, number.length);
},20);
});
}
解决问题3 https://nosir.github.io/cleave.js/
使用 cleave进行改进,最近看一下源码
网友评论