Angular form validation to validate the phone number
Asked Answered
D

8

12

I am trying to validate the phone number using regex expression in angular

HTML content

<div class="form-group row">
                <input type="text" class="form-control" appPhoneMask placeholder="Mobile Number" autocomplete="off"
                    [ngClass]="{ 'is-invalid': (f.inputCountryCode.errors && mobileNumberform.submitted) }"
                    formControlName="inputCountryCode">
                <div *ngIf="(f.inputCountryCode.invalid ) || (f.inputCountryCode.invalid && (f.inputCountryCode.dirty || f.inputCountryCode.touched))"
                    class="invalid-feedback">
                    <div *ngIf="f.inputCountryCode.errors.required">This field is required.</div>
                    <div *ngIf="f.inputCountryCode.errors.pattern">Invalid phone number.</div>
                </div>
            </div>

TS code

 this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{12}")]]
    });

The validation pattern should allow numeric number with space because I am using the phone number masking which add space after 3 digits.

enter image description here

The pattern is not working keep getting phone numner validation false

Angular 4 Mobile number validation

Regex for field that allows numbers and spaces

Masking directive

export class PhoneMaskDirective {

  constructor(public ngControl: NgControl) { }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }


  onInputChange(event, backspace) {
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = '';
    } else if (newVal.length <= 3) {
      newVal = newVal.replace(/^(\d{0,3})/, '$1');
    } else if (newVal.length <= 6) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '$1 $2');
    } else if (newVal.length <= 9) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '$1 $2 $3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}
Dacca answered 2/12, 2019 at 4:11 Comment(7)
Are you using reactive forms?Creole
yes I am using reactive formDacca
Regex tries to match 12 characters of the proceeding token [0-9 ], but you input only 11 characters so it gives errorChatoyant
try stackblitz.com/edit/angular6-phone-maskOutgrow
Yes that the same one I am using but I have removed the brackets and hyphens and trying to do the phone number validationDacca
There is not an error in your directive. The error is in your regular expressionOutgrow
@Chatoyant I am entering the 12 characters in the input text box. Still, there is an error.Dacca
B
24

You can allow for:

  • 9999 9999
  • +61 2 9999 9999
  • (02) 9999 9999
  • 555-999-9999
Validators.pattern('^[- +()0-9]+$')
Berthold answered 6/1, 2021 at 3:55 Comment(1)
Thanks! Validators.pattern('[- +()0-9]{6,}') if you want to have at least 6 characters.Locarno
R
9

Your regex expression requires 12 symbols of [0-9 ], while you input contains only 11.

Update your regexp for inputCountryCode to "[0-9 ]{11}":

 this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern("[0-9 ]{11}")]]
    });

Or you can add a space after phone number in input, so it will be 12 symbols.

But I would prefer to use more specific regexp for phone number like '[0-9]{3} [0-9]{3} [0-9]{3}', because with your pattern phone number 11 1111 111 or 111111 are valid numbers

Rest answered 2/12, 2019 at 4:45 Comment(3)
That is not working. I have added the masking code can you let me know where I am making a mistakeDacca
You just shared the sample code from here. So the directive is right. Make sure you using it right in html, also check the naming of your form fields in html and how you fill the formRest
I have updated the HTML content as well, HTML content is fine with the form name and controls. There is something else wrong and I am not able to figure it outDacca
P
1

Just another idea, similarly, you can actually force entered value to keep phone format, this is an example of US format 123-123-1234. First we limit users input on numbers only :

//Number formatting in your .ts file
  public numbersOnlyValidator(event: any) {
    const pattern = /^[0-9\-]*$/;
    if (!pattern.test(event.target.value)) {
      event.target.value = event.target.value.replace(/[^0-9\-]/g, "");
    }
  }

and then, we add phone field with directive phoneMask - in html :

 <div class="form-group row">
           <input 
             type="text" 
             placeholder="phone number xxx-xxx-xxxx" 
             class="form-control" 
             id="phone" 
             name="phone" 
             maxlength="12"
            [(ngModel)]="phone" 
            phoneMask
            [ngClass]="{ 'is-invalid': phone.touched || form.submitted && phone.invalid }"
            #phone="ngModel" 
            phoneMask 
            (input)="numbersOnlyValidator($event)" />

            <div *ngIf="(phone.touched || form.submitted) &&
                phone.invalid" class="invalid-feedback">
                  <div *ngIf="phone.errors">
                    Please enter valid phone number.
                  </div>
                </div>
 </div>

Here you filter numbers only (input)="numbersOnlyValidator($event)"

Here is Directive phoneMask used in html where you actually format input into dashed pattern NNN-NNN-NNNN :

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[phoneMask]'
})
export class PhoneMasksDirective {

  constructor() { }

  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, '');

    if (trimmed.length > 12) {
      trimmed = trimmed.substr(0, 12);
    }
 
    trimmed = trimmed.replace(/-/g,'');

    let numbers = [];
    numbers.push(trimmed.substr(0,3));
    if(trimmed.substr(3,3)!=="")
    numbers.push(trimmed.substr(3,3));
    if(trimmed.substr(6,4)!="")
    numbers.push(trimmed.substr(6,4));
    input.value = numbers.join('-');

  }

}

DEMO stackblitz

Probability answered 8/2, 2021 at 22:16 Comment(0)
E
1
[- +()0-9]{10,12} // basic validation with limited to 10 to 12 numbers range

You can you one of these options

With .ts file

Validators.pattern('[- +()0-9]{10,12}')

With HTML file

<input type="text" formControlName="MobileNumber" required pattern="[- +()0-9]{10,12}">
Eury answered 2/10, 2022 at 2:29 Comment(0)
R
0

You can use

Validators.pattern("(09)[0-9 ]{9}")

example: 09112223333

conditions: number must be start with '09', should be numerical and fixed length (in this sample 11 digit)

Reduplication answered 5/5, 2020 at 18:34 Comment(0)
E
0

I use the library "phone".

npm install phone

To import:

import { phone } from 'phone';

To use:

let a = phone('(817) 569-8900', {country: 'USA'});
console.log(a)

Which will give a result like this:

{isValid: true, phoneNumber: '+18175698900', countryIso2: 'US', countryIso3: 'USA', countryCode: '+1'}
Evonneevonymus answered 8/2, 2023 at 14:34 Comment(0)
C
0

You can use

Validators.pattern('^(?!0+$)(?:\(?\+\d{1,3}\)?[- ]?|0)?\d{10}$')

For example +91-134567890

"+" or "0" in the beginning of the number, followed by the country code, and then a hyphen (optional) before the 10-digit number."

Chafee answered 27/7, 2023 at 8:29 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Preempt
D
-1

The issue was with

Validators.pattern("[0-9 ]{12}")

Replace it with

Validators.pattern(new RegExp("[0-9 ]{12}"))

Change code

this.$form = this.$builder.group({
      selectCountryCode: [null, Validators.required],
      inputCountryCode: [null, [Validators.required, Validators.pattern(new RegExp("[0-9 ]{12}"))]]
    });
Dacca answered 4/12, 2019 at 1:44 Comment(1)
This work for me, by adding new RegExp function, i modified this answer to suit my problem of email or phone Validators.pattern(new RegExp("([0-9 ]{11})|([a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3})"))Hadji

© 2022 - 2025 — McMap. All rights reserved.