Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Angular Phone Number Validation and E164 Formatting

written by Jeff Delaney
full courses and content on fireship.io

In this snippet, I provide examples of handling phone numbers in Angular. If you’re working with a phone API, such as Twilio, you will need to covert numbers to E164.

Template Driven Style

First, let’s model the data and create a method for E164 formatting.

export class PhoneNumber {
country: string;
area: string;
prefix: string;
line: string;
// format phone numbers as E.164
get e164() {
const num = this.country + this.area + this.prefix + this.line
return `+${num}`
}
}

In the component TypeScript.

@Component({
// ...omitted
})
export class PhoneComponent implements OnInit {

phoneNumber = new PhoneNumber()

}

In the HTML

<label for="phone">Phone Number</label><br>
<input type="text" [(ngModel)]="phoneNumber.country" placeholder="1" maxlength="2" pattern="[0-9]+">
<input type="text" [(ngModel)]="phoneNumber.area" placeholder="949" maxlength="3" pattern="[0-9]+">
<input type="text" [(ngModel)]="phoneNumber.prefix" placeholder="555" maxlength="3" pattern="[0-9]+">
<input type="text" [(ngModel)]="phoneNumber.line" placeholder="5555" maxlength="4" pattern="[0-9]+">

Reactive Style

Now let’s do the same basic thing with a reactive form.

export class PhoneComponent implements OnInit {

constructor(private fb: FormBuilder) { }

ngOnInit() {
this.buildForm()
}

buildForm() {
this.numberForm = this.fb.group({
country: this.validateMinMax(1, 2),
area: this.validateMinMax(3, 3),
prefix: this.validateMinMax(3, 3),
line: this.validateMinMax(4, 4)
});
}

// A helper to DRY the code
validateMinMax(min, max) {
return ['', [
Validators.required,
Validators.minLength(min),
Validators.maxLength(max),
Validators.pattern('[0-9]+') // validates input is digit
]]
}

// format to E164
get e164() {
const form = this.numberForm.value
const num = form.country + form.area + form.prefix + form.line
return `+${num}`
}
}

And in the HTML

<form [formGroup]="numberForm" (ngSubmit)="doSomething()" novalidate>
<input type="text" formControlName="country" placeholder="1">
<input type="text" formControlName="area" placeholder="916">
<input type="text" formControlName="prefix" placeholder="555">
<input type="text" formControlName="line" placeholder="5555">

<input type="submit">
</form>