Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Mobile number validation

Tags:

angular

I want to validate a mobile number using Angular 4 and it should not accept any characters other than numbers up to just 10 digits.

Below is my code ,

<input type="text" formControlName="mobileNo" minlength=10 maxlength=10>
like image 478
Sarvesh Redkar Avatar asked Sep 21 '17 08:09

Sarvesh Redkar


2 Answers

just add validators pattern

mobileNumber: new FormControl(null, [Validators.pattern("[0-9]{0-10}")])

and the type will be number and it will avoid accepting any character

like image 132
Khaled Ahmed Avatar answered Oct 21 '22 04:10

Khaled Ahmed


<input type="text" (keypress)="keyPress($event)" minlength=10 maxlength=10>


  keyPress(event: any) {
    const pattern = /[0-9\+\-\ ]/;

    let inputChar = String.fromCharCode(event.charCode);
    if (event.keyCode != 8 && !pattern.test(inputChar)) {
      event.preventDefault();
    }
  }
like image 33
ketan pradhan Avatar answered Oct 21 '22 03:10

ketan pradhan