isValidNumberForRegion.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import isViablePhoneNumber from '../helpers/isViablePhoneNumber.js';
  2. import parseNumber from '../parse.js';
  3. import _isValidNumberForRegion from './isValidNumberForRegion_.js'; // This function has been deprecated and is not exported as
  4. // `isValidPhoneNumberForCountry()` or `isValidPhoneNumberForRegion()`.
  5. //
  6. // The rationale is:
  7. //
  8. // * We don't use the "region" word, so "country" would be better.
  9. //
  10. // * It could be substituted with:
  11. //
  12. // ```js
  13. // export default function isValidPhoneNumberForCountry(phoneNumberString, country) {
  14. // const phoneNumber = parsePhoneNumber(phoneNumberString, {
  15. // defaultCountry: country,
  16. // // Demand that the entire input string must be a phone number.
  17. // // Otherwise, it would "extract" a phone number from an input string.
  18. // extract: false
  19. // })
  20. // if (!phoneNumber) {
  21. // return false
  22. // }
  23. // if (phoneNumber.country !== country) {
  24. // return false
  25. // }
  26. // return phoneNumber.isValid()
  27. // }
  28. // ```
  29. //
  30. // * Same function could be used for `isPossiblePhoneNumberForCountry()`
  31. // by replacing `isValid()` with `isPossible()`.
  32. //
  33. // * The reason why this function is not exported is because its result is ambiguous.
  34. // Suppose `false` is returned. It could mean any of:
  35. // * Not a phone number.
  36. // * The phone number is valid but belongs to another country or another calling code.
  37. // * The phone number belongs to the correct country but is not valid digit-wise.
  38. // All those three cases should be handled separately from a "User Experience" standpoint.
  39. // Simply showing "Invalid phone number" error in all of those cases would be lazy UX.
  40. export default function isValidNumberForRegion(number, country, metadata) {
  41. if (typeof number !== 'string') {
  42. throw new TypeError('number must be a string');
  43. }
  44. if (typeof country !== 'string') {
  45. throw new TypeError('country must be a string');
  46. } // `parse` extracts phone numbers from raw text,
  47. // therefore it will cut off all "garbage" characters,
  48. // while this `validate` function needs to verify
  49. // that the phone number contains no "garbage"
  50. // therefore the explicit `isViablePhoneNumber` check.
  51. var input;
  52. if (isViablePhoneNumber(number)) {
  53. input = parseNumber(number, {
  54. defaultCountry: country
  55. }, metadata);
  56. } else {
  57. input = {};
  58. }
  59. return _isValidNumberForRegion(input, country, undefined, metadata);
  60. }
  61. //# sourceMappingURL=isValidNumberForRegion.js.map