Skip to content

Instantly share code, notes, and snippets.

@ng-hai
Last active December 7, 2020 10:44
Show Gist options
  • Save ng-hai/5de3cef73f0996ec2dfd52623ba3f988 to your computer and use it in GitHub Desktop.
Save ng-hai/5de3cef73f0996ec2dfd52623ba3f988 to your computer and use it in GitHub Desktop.
Vietnamese mobile phone number validation
const COUNTRY_DIALING_CODE = "84"
const NETWORKS_PREFIX = [
// Viettel
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"86",
"96",
"97",
"98",
// MobiFone
"70",
"76",
"77",
"78",
"79",
"89",
"90",
"93",
// Vinaphone
"81",
"82",
"83",
"84",
"85",
"88",
"91",
"94",
// Vietnamobile
"56",
"58",
"92",
// Gmobile
"59",
"95",
"99",
]
function isNotPhoneNumber(value) {
return value.split("").some((character) => Number.isNaN(Number(character)))
}
export default function isPhoneNumberValid(value) {
if (!value) {
return false
}
// Remove whitespace and plus sign
let formattedNumber = String(value).replace(/\s|\+/g, "")
const isNotANumber = isNotPhoneNumber(formattedNumber)
if (isNotANumber) {
return false
}
// Length should be from 9 to 10 numbers
// without COUNTRY_DIALING_CODE and zero number
const startsWithCountryDialingCode = formattedNumber.startsWith(
COUNTRY_DIALING_CODE,
)
if (startsWithCountryDialingCode) {
formattedNumber = formattedNumber.substr(COUNTRY_DIALING_CODE.length)
}
const startsWithZero = formattedNumber.startsWith("0")
if (startsWithZero) {
formattedNumber = formattedNumber.substr(1)
}
// Have right prefix
const networkPrefix = NETWORKS_PREFIX.find((prefix) =>
formattedNumber.startsWith(prefix),
)
if (!networkPrefix) {
return false
}
// Final length is always 7 numbers after remove NETWORKS_PREFIX
// 84 166XXXXXXX
// 84 96XXXXXXX
formattedNumber = formattedNumber.substr(networkPrefix.length)
if (formattedNumber.length !== 7) {
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment