Skip to content

Commit

Permalink
Update PhoneNumber.ts
Browse files Browse the repository at this point in the history
Updated regex for E.164 compliant to support phone number with extension.
  • Loading branch information
nthombare-mdsol authored Jan 28, 2025
1 parent 5471b05 commit 202ae3b
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/scalars/PhoneNumber.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { GraphQLScalarType, Kind } from 'graphql';
import { createGraphQLError } from '../error.js';

const PHONE_NUMBER_REGEX = /^\+[1-9]\d{6,14}$/;
// The regex supports all phone numbers compliant with the E.164 international format standard,
// which includes country codes (Optional), area codes, and local numbers and extension (optional). For more information on E.164 formatting,
// Regex: https://regex101.com/r/nol2F6/1
// Ex. +62 (21) 9175 5194, 2191755194, +1 123-456-7890 12345, +1 (123) 456-7890
const PHONE_NUMBER_REGEX = /^\+?\d{1,3}(\-|\x20)?\(?\d+\)?((\-|\x20)?\d+)+$/;

export const GraphQLPhoneNumber = /*#__PURE__*/ new GraphQLScalarType({
name: 'PhoneNumber',
Expand All @@ -16,7 +20,7 @@ export const GraphQLPhoneNumber = /*#__PURE__*/ new GraphQLScalarType({

if (!PHONE_NUMBER_REGEX.test(value)) {
throw createGraphQLError(
`Value is not a valid phone number of the form +17895551234 (7-15 digits): ${value}`,
`Invalid phone number: ${value}. Please ensure it's in a valid format. The country code is optional, and Spaces and dashes are allowed. Examples: +1 (123) 456-7890, +44 (20) 2121 2222, or 123 456-7890.`,
);
}

Expand All @@ -30,7 +34,7 @@ export const GraphQLPhoneNumber = /*#__PURE__*/ new GraphQLScalarType({

if (!PHONE_NUMBER_REGEX.test(value)) {
throw createGraphQLError(
`Value is not a valid phone number of the form +17895551234 (7-15 digits): ${value}`,
`Invalid phone number: ${value}. Please ensure it's in a valid format. The country code is optional, and Spaces and dashes are allowed. Examples: +1 (123) 456-7890, +44 (20) 2121 2222, or 123 456-7890.`,
);
}

Expand All @@ -47,7 +51,7 @@ export const GraphQLPhoneNumber = /*#__PURE__*/ new GraphQLScalarType({

if (!PHONE_NUMBER_REGEX.test(ast.value)) {
throw createGraphQLError(
`Value is not a valid phone number of the form +17895551234 (7-15 digits): ${ast.value}`,
`Invalid phone number: ${ast.value}. Please ensure it's in a valid format. The country code is optional, and Spaces and dashes are allowed. Examples: +1 (123) 456-7890, +44 (20) 2121 2222, or 123 456-7890.`,
{ nodes: ast },
);
}
Expand Down

0 comments on commit 202ae3b

Please sign in to comment.