skip to Main Content

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


  1. 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:

        import { Validators } from '@angular/forms';
    
    // Define the pattern for phone numbers with an optional extension
    const phonePatternWithExt = /^((d{3}))d{3}-d{4}( x d{5})?$/;
    
    // Set up the validator using the pattern
    phone: ['', [Validators.pattern(phonePatternWithExt)]],
    
    Login or Signup to reply.
  2. 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:

    <input type="text" placeholder="Phone" class="form-control" formControlName="phone"
           [ngClass]="{ 'is-invalid': (isSaved && contactForm.get('phone').errors)}">
    <div *ngIf="isSaved && contactForm.get('phone').errors" class="invalid-feedback">
      Invalid phone number.
    </div>
    

    Make changes in your component ts file like follow:

      contactForm: FormGroup;
      isSaved: boolean = false;
    
      constructor(private formBuilder: FormBuilder) { }
    
      ngOnInit(): void {
        this.contactForm = this.formBuilder.group({
          phone: ['', [Validators.pattern(this.getPhonePattern())]]
        });
      }
    
      getPhonePattern(): string {
        return '^\(?(\d{3})\)?[-. ]?(\d{3})[-. ]?(\d{4})( x \d{1,5})?$';
      }
    
      onSubmit() {
        this.isSaved = true;
        if (this.contactForm.valid) {
            You can call your API or whatever your process it
        }
      }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search