phone-number-utils.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Regex that holds the characters used to separate segments of a phone number
  2. var separatorCharRe = /[-. ]/;
  3. // Regex that specifies any delimiter char that allows us to treat the number as
  4. // a phone number rather than just any other number that could appear in text.
  5. var hasDelimCharsRe = /[-. ()]/;
  6. // "Pause" and "Wait" control chars
  7. var controlCharRe = /[,;]/;
  8. // Over the years, many people have added to this regex, but it should have been
  9. // split up by country. Maybe one day we can break this down.
  10. var mostPhoneNumbers = /(?:(?:(?:(\+)?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})|(?:(\+)(?:9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)[-. ]?(?:\d[-. ]?){6,12}\d+))([,;]+[0-9]+#?)*/;
  11. // Regex for Japanese phone numbers
  12. var japanesePhoneRe = /(0([1-9]-?[1-9]\d{3}|[1-9]{2}-?\d{3}|[1-9]{2}\d{1}-?\d{2}|[1-9]{2}\d{2}-?\d{1})-?\d{4}|0[789]0-?\d{4}-?\d{4}|050-?\d{4}-?\d{4})/;
  13. // Combined regex
  14. var validPhoneNumberRe = new RegExp("^".concat(mostPhoneNumbers.source, "|").concat(japanesePhoneRe.source, "$"));
  15. /**
  16. * Determines if the character is a phone number separator character (i.e.
  17. * '-', '.', or ' ' (space))
  18. */
  19. export function isPhoneNumberSeparatorChar(char) {
  20. return separatorCharRe.test(char);
  21. }
  22. /**
  23. * Determines if the character is a control character in a phone number. Control
  24. * characters are as follows:
  25. *
  26. * - ',': A 1 second pause. Useful for dialing extensions once the main phone number has been reached
  27. * - ';': A "wait" that waits for the user to take action (tap something, for instance on a smart phone)
  28. */
  29. export function isPhoneNumberControlChar(char) {
  30. return controlCharRe.test(char);
  31. }
  32. /**
  33. * Determines if the given phone number text found in a string is a valid phone
  34. * number.
  35. *
  36. * Our state machine parser is simplified to grab anything that looks like a
  37. * phone number, and this function confirms the match.
  38. */
  39. export function isValidPhoneNumber(phoneNumberText) {
  40. // We'll only consider the match as a phone number if there is some kind of
  41. // delimiter character (a prefixed '+' sign, or separator chars).
  42. //
  43. // Accepts:
  44. // (123) 456-7890
  45. // +38755233976
  46. // Does not accept:
  47. // 1234567890 (no delimiter chars - may just be a random number that's not a phone number)
  48. var hasDelimiters = phoneNumberText.charAt(0) === '+' || hasDelimCharsRe.test(phoneNumberText);
  49. return hasDelimiters && validPhoneNumberRe.test(phoneNumberText);
  50. }
  51. //# sourceMappingURL=phone-number-utils.js.map