Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RegEx Based Verify China Phone Number
// includes China Mobile, China Unicom, China Telecom
const isChinaPhoneNumber = phone => /^1(?:70\d|(?:9[89]|8\d|7[135-8]|66|5[0-35-9])\d|3(?:4[0-8]|[0-35-9]\d))\d{7}$/.test(phone)
const prefixGroups = {
"China Mobile": [
1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348,
135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159,
178, 182, 183, 184, 187, 188, 198
],
"China Mobile (MVNO)": [1703, 1705, 1706],
// "China Mobile (Data-only)": [1440, 147, 148],
"China Unicom": [130, 131, 132, 155, 156, 166, 175, 176, 185, 186],
"China Unicom (MVNO)": [1704, 1707, 1708, 1709, 171],
// "China Unicom (Data-only)": [145, 146],
"China Telecom": [133, 153, 173, 177, 180, 181, 189, 199],
"China Telecom (MVNO)": [1700, 1701, 1702],
// "China Telecom (Data-only)": [149, 1410],
// "China Telecom (Satellite)": [1349, 17400, 17401, 17402, 17403, 17404, 17405]
}
const buildRegExp = prefixs => {
prefixs.sort()
const mapped = prefixs.map(String).map(prefix => prefix.padEnd(11, 'X'))
const replaced = require('regexgen')(mapped).source
.replace(/\[0-9]/g, 'X')
.replace(/X+/g, m => `\\d{${m.length}}`)
.replace(/\\d\{1}/g, '\\d')
return new RegExp(`^${replaced}$`)
}
const makeSingleRegExp = (prefixGroups) => {
const prefixs = Object.values(prefixGroups)
.reduce((prefixs, items) => [...prefixs, ...items], [])
return buildRegExp(prefixs)
}
const makeGroupRegExp = (prefixGroups) => {
return Object.keys(prefixGroups)
.reduce((group, name) => Object.assign(group, {[name]: buildRegExp(prefixGroups[name])}), {})
}
console.log('Single RegExp:\n')
console.log(makeSingleRegExp(prefixGroups))
console.log(`\n${'-'.repeat(20)}\n`)
console.log('Group RegExp:\n')
console.log(makeGroupRegExp(prefixGroups))
@x13945

This comment has been minimized.

Copy link

commented Apr 23, 2018

Below code use "182" twice, do you mean "182" and "183"?

"China Mobile": [
        1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348,
        135, 136, 137, 138, 139, 150, 151, 152, 157, 158, 159,
        178, 182, 182, 184, 187, 188, 198
],
@septs

This comment has been minimized.

Copy link
Owner Author

commented May 2, 2018

@x13945 fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.