I want these type format and extension number are optional
(1800)-555-1212 X 65432
HTML:
<input type="text" placeholder="Phone" min="10" max="15" class="form-control" formControlName="phone"
mask="(000)-000-0000 x 00000"
[ngClass]="{ 'is-invalid': (isSaved && contactForm.phone.errors)}">
Typescript:
phone: ['', [Validators.pattern(this.commonRegex.PhoneWithExtRegex)]],
/(?([0-9]{3}))?([ .-]?)([0-9]{3})2([0-9]{4})+x([0-4]{5})/
2
Answers
To format phone numbers in the specified format with an optional extension number, you can use regular expressions in TypeScript. Here’s how you can achieve this:
You should use reactive forms as you can make changes easily and no matter how large form is, you would work around it easily. Create a form builder at the start and use its properties. And make the regex as per your need.
in your component HTML file it should be like:
Make changes in your component ts file like follow:
This is the best way to handle inputs or form I have been implementing in my project. Hope it helps and let me know if you need any more help.