Validating phone numbers in an Angular app is vital for clean data and user contact. We will cover four ways to handle this, providing code for each method. Then, we'll explore the shortcomings of these techniques and introduce how Abstract API offers a more reliable alternative.
How to Implement Phone Number Validation in Angular
Here are four common methods to validate phone numbers in an Angular application. Each approach offers a different way to integrate validation logic directly into your forms.
Reactive-Forms Pattern Validator
This method employs Angular’s built-in “Validators.pattern” with a regular expression that matches the international E.164 dial string. This approach is efficient and keeps the control synchronous, with “FormsModule” and “ReactiveFormsModule” as the only dependencies.
The control becomes valid only when the input text complies with the E.164 standard, which specifies 1 to 15 digits with an optional leading “+” symbol. A program example shows this implementation.
// TypeScript
const e164 = /^\+?[1-9]\d{1,14}$/;
this.form = this.fb.group({
phone: ['', [Validators.required, Validators.pattern(e164)]]
});
// Template
<input formControlName="phone" type="tel">
Custom Validator with Google-libphonenumber
When simple pattern matches are insufficient, you can parse and validate numbers with Google’s canonical library. This approach uses a custom validator function that delegates the logic to “google-libphonenumber”.
The function attempts to parse the input value based on a specified region, like “US”, and then checks if the number is valid. The validator remains synchronous and handles country rules, short codes, and number lengths, as detailed on the npm package page.
// TypeScript
import { PhoneNumberUtil } from 'google-libphonenumber';
import { AbstractControl, ValidationErrors } from '@angular/forms';
const util = PhoneNumberUtil.getInstance();
export function e164Validator(region = 'US') {
return (c: AbstractControl): ValidationErrors | null => {
try {
const n = util.parseAndKeepRawInput(c.value, region);
return util.isValidNumber(n) ? null : { phone: 'invalid' };
} catch {
return { phone: 'invalid' };
}
};
}
this.form = this.fb.group({ phone: ['', [Validators.required, e164Validator('US')]] });
Attribute Directive That Implements Validator
A directive offers a reusable way to attach validation to any native or Material input, which avoids modifications to component code. The directive implements the “Validator” interface and is registered as a provider with “NG_VALIDATORS”.
This registration ensures any control with the directive attribute participates in the standard Angular validation pipeline. The directive’s “validate” method tests the control’s value against a predefined regular expression, as shown in a similar program example.
// TypeScript
@Directive({
selector: '[appPhoneNumber]',
providers: [{ provide: NG_VALIDATORS, useExisting: PhoneNumberDirective, multi: true }]
})
export class PhoneNumberDirective implements Validator {
private rx = /^\d{10}$/; // US local pattern
validate(ctrl: AbstractControl) {
return this.rx.test(ctrl.value) ? null : { phone: 'invalid' };
}
}
// HTML
<input type="tel" appPhoneNumber>
Drop-in Component: ngx-intl-tel-input
This package provides a complete component that wraps an input field. It includes a country picker, placeholder management, input masks, and Google’s validation logic already configured for use.
After installation, you can use the “ngx-intl-tel-input” component in your template. The component automatically surfaces “FormControl” errors, so it integrates with both reactive and template-driven forms. More information is available on the ngx-intl-tel-input package page.
// Installation
npm i intl-tel-input google-libphonenumber ngx-intl-tel-input
// Module Import
import { NgxIntlTelInputComponent } from 'ngx-intl-tel-input';
// Template
<ngx-intl-tel-input
[preferredCountries]="['us','gb']"
formControlName="phone">
</ngx-intl-tel-input>
Challenges of Phone Number Validation in Angular
While these methods seem straightforward, they introduce complexities that can compromise data quality and user experience. These approaches often create more problems than they solve.
- International numbering rules change by country and over time. Custom validators or google-libphonenumber need fresh metadata. When metadata lags, valid inputs fail, and users blame the front end.
- Third-party components like ngx-intl-tel-input automatically reformat dial codes. These side effects can duplicate prefixes or alter the control value, which causes inconsistent validation results between cycles.
- Users often type a local pattern, but applications must store an E.164 string. The constant conversion fights Angular’s change detection and can leave the FormControl out of sync.
- Pattern validation, used in the reactive-forms method, cannot prove a number is live. A number might pass the regex test but bounce in production because it is prepaid or reassigned.
Validate Phone Numbers with Abstract API
Implement phone number validation in your Angular app to ensure you only receive valid numbers.
Get started for free
How Abstract API Handles Phone Number Validation in Angular
Abstract API addresses the core weaknesses of traditional methods through authoritative verification and broad international support.
- It queries live numbering-plan data to confirm a number's existence and reachability. This process returns a boolean valid flag, carrier details, line type, and geolocation to stop invalid numbers before an SMS or call attempt.
- A single REST call interprets any international format. This action returns both international and local formats for display or storage and removes the need for custom pattern upkeep, which often bloats application bundles.
- Validation occurs server-side over HTTPS. This method keeps business rules off the client, ensures a lean bundle size, and allows for centralized error responses.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract’s capabilities, you can add its phone number validation to your project with ease. To prepare your development environment, follow these steps:
- Sign up on Abstract API, enable Phone Validation, and copy your API key.
- Import HttpClientModule in app.module.ts.
- Store the key in your environment.ts file.
- Generate a service with the command: ng generate service services/phone-validator.
- Implement the phone validator inside the new service.
import { HttpClient } from '@angular/common/http';
@Injectable({providedIn:'root'})
export class PhoneValidatorService {
private endpoint = 'https://phonevalidation.abstractapi.com/v1/';
constructor(private http: HttpClient) {}
validate(phone: string) {
const params = { api_key: environment.abstractKey, phone };
return this.http.get(this.endpoint, { params });
}
}
Sample Phone Number Validation with Abstract API
The API returns a JSON object that contains key details about the number. The boolean "valid" field confirms if delivery is possible. The "format" object provides both international and local versions of the number for display or storage. Other fields like "country", "location", "type", and "carrier" support geo-checks, SMS gates, and fraud analysis.
{
"phone": "14152007986",
"valid": true,
"format": { "international": "+14152007986", "local": "(415) 200-7986" },
"country": { "code": "US", "name": "United States", "prefix": "+1" },
"location": "California",
"type": "mobile",
"carrier": "T-Mobile USA, Inc."
}
Final Thoughts
Traditional phone validation relies on pattern matches, which cannot confirm if a number is active or reachable. This approach also requires complex, country-specific rules that bloat applications. Abstract API uses live data to provide authoritative verification through a single, simple call.
To reliably validate user phone numbers, consider the creation of an account on Abstract API to get your free API key.
Validate Phone Numbers with Abstract API
Validate phone numbers in your Angular project to improve data quality and user experience.
Get started for free