weex实现少数民族姓名正则
少数民族的姓名中间带点‘·’,比如热巴全名 迪丽热巴·迪力木拉提
要求:
1.允许输入汉字、任意格式的圆点,圆点只能出现在汉字中间;
2.不允许输入原点以外的其他特殊字符、不允许有数字、字母、空格;
3.姓名总长度长度50个字符(25个汉字) ;
4.任意格式的原点统一由系统转译为·(中圆点)后存储,姓名反显统一使用·(中圆点);
- 使用weex提供的setTextFormatter属性限制ref对应的输入框允许输入的内容:
//限制输入内容
//formatRule内容为仅允许输入·•‧•⋅ㆍ・.●各种点以及汉字
this.$refs.userNameInput.setTextFormatter({
formatRule: '/([^·•‧•⋅ㆍ・.●\u4e00-\u9fa5\\*])(?!$)/g', //格式化匹配的正则表达式
formatReplace: '', //格式化匹配后用于替换的内容
recoverRule: '', //从格式化后的内容还原原始内容的正则表达式
recoverReplace: '', //还原原始内容时用于替换的内容
})
- 使用onchange方法+replace来控制输入完毕后的控制:
// 姓名正则校验
// pattern1 将各种点替换为中圆点,
// / /g 将空格替换为空
// /\·{2,}/g 将两个以上连续的点替换为一个点
// /\·+$/ 将最后面的点替换为空
// /^\·+/ 将最前面的点替换为空
// 截取前50位
nameInputReg(e) {
let val = e.value
let pattern1 = /[•-‧•⋅ㆍ・●]/g
this.userName = val
.replace(pattern1, '·')
.replace(/ /g, '')
.replace(/\·{2,}/g, '·')
.replace(/\·+$/, '')
.replace(/^\·+/, '')
.slice(0, 50)
return this.userName
},
- 最后在提交的时候再进行一遍校验,给他卡的死死的
let nameReg = /^([\u4e00-\u9fa5]|·|(\(+\))|(\([\u4e00-\u9fa5]+\)))+$/
if (!nameReg.test(this.userName) || this.userName.length > 50) {
this.alertMsg('姓名输入不合法')
return
} else if (this.userName.replace(/\·/g, '').length > 25) {
this.alertMsg('姓名最多输入25个汉字')
return
}
- 补充
weex 的setTextFormatter属性在iOS原生键盘不支持输入中文 要了命了
最后改成不做输入限制 仅做失去焦点的限制
// 姓名正则校验
nameInputReg(e) {
let val = e.value
let pattern1 = /[•‧•⋅ㆍ・.●]/g
let pattern2 = /[^·•‧•⋅ㆍ・.●\u4e00-\u9fa5]/g
this.userName = val
.replace(pattern2, '')
.replace(pattern1, '·')
.replace(/ /g, '')
.replace(/\·{2,}/g, '·')
.replace(/\·+$/, '')
.replace(/^\·+/, '')
.slice(0, 50)
return this.userName
},