This tutorial covers how to format a phone number on the fly as a user types their phone number. Below is an example of what we’ll build. Phone number input formatter

Installation

First we’ll need to start by installing angular2-text-mask:

npm install angular2-text-mask --save

Lets code it!

We’ll navigate to the app.module.ts file and import the TextMaskModule and add the module to our imports:

...
import { TextMaskModule } from 'angular2-text-mask';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    TextMaskModule
  ],
  ...
})
export class AppModule { }

We’ll need to generate a mask that angular2-text-mask uses to format the phone number properly. In this tutorial we’ll use phone number masks, however masks can be customized in RegEx format and can create formatters for zipcodes, pin codes, etc.

International format - +1 (123) 456-7890

['+', '1', ' ', '(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]

Regular format - (123) 456-7890

['(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]

We’ll navigate to the component that contains the input we want formatting applied to and add the mask as a variable.

@Component({
    ...
})
export class ExampleComponent{
    mask: any[] = ['+', '1', ' ', '(', /[1-9]/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/];
    ...
}

Lastly, We’ll add the [textMask] directive property to input within the template.

<input type="text"
       placeholder="+1 (123) 456-7890"
       [textMask]="{mask: mask}"/>

Optional

As an added measure to prevent users from submitting a phone number that isn’t valid, we’ll add a pattern attribute. First the form must given a name using formGroup to the form tag and enable the submit button once the phone number input is valid.

<form [formGroup]="form-name" (ngSubmit)="onSubmit()">
    <input type="text"
           placeholder="+1 (123) 456-7890"
           [textMask]="{mask: mask}"
           pattern="\+\d \(\d{3}\) \d{3}-\d{4}"/>
    <button type="submit" [disabled]="!form-name.valid" class="btn btn-default">Submit</button>
</form>

The RegEx \+\d \(\d{3}\) \d{3}-\d{4} verifies that the phone number is in proper format and sets form-name.valid to true when the phone number is in valid format.

Note

This approach doesn’t format input POSTed manually. We recommend a check at the api endpoint to ensure input is formatted properly to maintain consistency across the database.