Reputation: 45
I am trying to create pattern for phone numbers and I want to look it like this:
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>
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
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