Search code examples
regexangularangular-materialangular-reactive-formsangular-forms

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}$"

Solution

  • 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