bot_73
bot_73

Reputation: 45

FormControl.Validators.pattern does not work correctly, while Regex with same string shows that data matches

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?

Upvotes: -1

Views: 182

Answers (1)

Ricardo Rocha
Ricardo Rocha

Reputation: 16216

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}')]);

Upvotes: -2

Related Questions