Anoop Chauhan
Anoop Chauhan

Reputation: 13

How to validate mobile number on angular material reactive form?

app.component.ts

phoneFormControl = new FormControl('', [
Validators.required,
Validators.pattern("[6-9]\d{9}")
])

app.component.html

<mat-form-field>
    <input matInput placeholder="Phone Number" [formControl]="phoneFormControl>
    <mat-error *ngIf="phoneFormControl.hasError('required')">
         Phone Number is <strong>required</strong>
    </mat-error>
</mat-form-field>

Error on form submission

pattern:
   actualValue: "9120227914"
   requiredPattern: "^[6-9]d{9}$"

Upvotes: 0

Views: 6328

Answers (1)

developer033
developer033

Reputation: 24874

Since your pattern is a string, it should have the backslash escaped.

So, instead of Validators.pattern("[6-9]\d{9}"), you want Validators.pattern("[6-9]\\d{9}").

Sample:

readonly phoneFormControl = new FormControl('', [
  Validators.required, Validators.pattern(("[6-9]\\d{9}"))
]);

Working demo

Upvotes: 3

Related Questions