TypeScript Function Validates a Phone Number

Posted 05/04/2019 10:02 AM by Corey Klass

Here is a TypeScript function that you can use to validate telephone numbers in Angular:

// validates a phone number
static phoneValidate(textToValidate: string, maxDigits?: number): boolean {
  if (!maxDigits) {
    maxDigits = 20;
  }

  let validFlag = true;


  // test for invalid characters
  if (validFlag) {
    const validCharacters = /[0-9\(\)\ \-\.]/g;
    const invalidText = textToValidate.replace(validCharacters, '');

    if (invalidText !== '') {
      validFlag = false;
    }
  }


  // test for a valid phone number
  if (validFlag) {
    const nonNumericCharacters = /[^0-9]]/g;
    let rawText = textToValidate.replace(nonNumericCharacters, '');

    // if the first character is a 1
    if (rawText.substr(0, 1) === '1') {
      rawText = rawText.substr(1, rawText.length - 1);
    }

    if (rawText.length < 10) {
      validFlag = false;

    } else if (rawText.length > maxDigits) {
      validFlag = false;
    }
  }


  return validFlag;
}

Below is a description of what's going on.

static phoneValidate(textToValidate: string, maxDigits?: number): boolean {
  if (!maxDigits) {
    maxDigits = 20;
  }

The default maximum number of digits has been set to 20 here, but you can supply an alternate number of digits for specific scenarios.

  let validFlag = true;

Default that the phone number is true

    const validCharacters = /[0-9\(\)\ \-\.]/g;
    const invalidText = textToValidate.replace(validCharacters, '');

    if (invalidText !== '') {
      validFlag = false;
    }

The validCharacters regular expression defines the following characters as valid: The digits 0-9, an open parenthesis "(", a closed parenthesis ")", a space, a dash, and a period. It then replaces the valid characters with empty strings, leaving only potentially invalid characters. If the invalid character string is anything other than empty, the phone number string is not valid.

  // test for a valid phone number
  if (validFlag) {
    const nonNumericCharacters = /[^0-9]/g;
    let rawText = textToValidate.replace(nonNumericCharacters, '');

If the phone number is valid up to this point, remove any non-numeric characters from the input string.

    // if the first character is a 1
    if (rawText.substr(0, 1) === '1') {
      rawText = rawText.substr(1, rawText.length - 1);
    }

In the US, a "1" at the beginning of the phone number is a special digit, so remove it. You may need to customize this based on your country.

    if (rawText.length < 10) {
      validFlag = false;

In the US, telephone numbers are at least 10 digits long. If the numeric string is less than 10 characters, it is not valid.

    } else if (rawText.length > maxDigits) {
      validFlag = false;
    }

If the numeric string is longer than the maximum digits allowed, the telephone number is not valid.