Sunday, 3 January 2021

Regular expression to validate US phone numbers in Angular?

Pattern: - 

"^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$" 

OR 

"^\\(?([2-9][0-8][0-9])\\)?[-. ]?([2-9][0-9]{2})[-.]?([0-9]{4})$"

Valid

1. (123) 123-1234

2. 123-123-1234

Component.ts

import { FormControlFormGroupValidators } from '@angular/forms';

formFormGroup;

createForm() {
    this.formnew FormGroup({
      Phone: new FormControl('',Validators.pattern("^(\\([0-9]{3}\\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$"))
    });
}

ngOnInit() {
    this.createForm();
}

API reference

import { FormsModule, ReactiveFormsModule } from '@angular/forms'

import { MatFormFieldModule from '@angular/material/form-field'
import { MatInputModule } from "@angular/material/input";

Component.html

<form [formGroup]="form" autocomplete="off">
 
<mat-form-field>
<input matInput placeholder="Phone" formControlName="Phone">
<mat-error *ngIf="form.get('Phone').hasError('pattern')">
    Phone is invalid.
</mat-error>
</mat-form-field>

</form>

Here is a little stackblitz demo:

angular-validate-us-phone - StackBlitz

No comments:

Post a Comment