-1

I am trying to create pattern for phone numbers and I want to look it like this:

  1. +375 29 555 55 55
  2. 80-33-555-555-55
  3. +375-25-555-55-55
  4. 80445555555 etc.

I wrote following code:

.ts

  phoneFormControl = new FormControl('', [Validators.required, Validators.pattern('^\s*(\+375|80)\s?-?\s?(25|29|33|44)\s?-?\s?\d{3}\s?-?\s?\d{2}\s?-?\s?\d{2}$')]);

.html

<mat-form-field class="example-full-width">
      <mat-label>Телефон</mat-label>
      <input matInput [(ngModel)]="this.profileData.Phone" [formControl]="phoneFormControl" maxlength="30">
      <mat-error *ngIf="phoneFormControl.hasError('pattern')">Номер не соответствует формату!</mat-error>
    </mat-form-field>

But i have error: enter image description here

A also tried to change .ts to this phoneFormControl = new FormControl('', [Validators.required, Validators.pattern('^\s*80\s?-?\s?(25|29|33|44)\s?-?\s?\d{3}\s?-?\s?\d{2}\s?-?\s?\d{2}$')]); expecting that it will be work only with 80... Error disappeared, but it does not work correctly now (I used 80295555555 80-29-555-55-55 80 33 555 55 55)...

Also I have tried this:

 phoneFormControl = new FormControl('', [Validators.required, Validators.pattern('/^\s*([+]{1}375|80)\s?-?\s?(25|29|33|44)\s?-?\s?\d{3}\s?-?\s?\d{2}\s?-?\s?\d{2}$/')]);

What can I do to get expected result?

bot_73
  • 45
  • 6

1 Answers1

-2

I'm not under 100% sure, but it seems that you have a typo.

If you check the example in the official documentation, you see that you don't need ^ and $ at the beginning and end of your regex string.

So, probably, you just need to change your code to this:

phoneFormControl = new FormControl('', [Validators.required, Validators.pattern('\s*(\+375|80)\s?-?\s?(25|29|33|44)\s?-?\s?\d{3}\s?-?\s?\d{2}\s?-?\s?\d{2}')]);
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • 1
    It is not a problem to have `^` and `$` in this pattern (though they are redundant in this context). At any rate, your current solution - `'\s*(\+375|80)\s?-?\s?(25|29|33|44)\s?-?\s?\d{3}\s?-?\s?\d{2}\s?-?\s?\d{2}'` - throws the same exception. – Wiktor Stribiżew Feb 28 '21 at 16:47