11位手机号码判断并不简单,关键是要尽可能的考虑到所有情况。其关键还在于正则表达式的使用:
valid_mobile:function(){
const regex = /^(((1[35789][0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
console.log(this.data.newBase.mobile)
if (this.data.newBase.mobile == undefined)
{
console.log(wx.getStorageSync('msg'))
this.setData({
err_msg: '手机号不能为空'
})
return false
}
console.log(wx.getStorageSync('msg'), this.data.newBase.mobile)
if (this.data.newBase.mobile.length !== 0 && this.data.newBase.mobile.length !== 11) {
this.setData({
mobileLength: true,
err_msg: '手机长度有误'
})
return false
} else if (this.data.newBase.mobile.length !== 0 && !regex.test(this.data.newBase.mobile)) {
this.setData({
mobileFormat: true,
err_msg: '手机号有误'
})
return false
}
return true
},
核心代码在这一行:
const regex = /^(((1[35789][0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
第一组是三个或然选项,1打头,13×,15×,18*等等,然后是八位数字的后缀。其中|为或然选择,^表示从头匹配, $表示匹配到结尾,如此则不需要去掉匹配字符串的前后空格。
这样虽然有点严格,但规矩严格一点没坏处。