Angular 4 Mobile number validation

2020-06-17 15:14发布

问题:

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>

回答1:

<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();
    }
  }


回答2:

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



回答3:

The keyPress event worked for chrome however does not work for Firefox. In chrome key presses like backspace and arrow key events are ignored by default and does not run the function however in Firefox it runs and these do not work. I added a small line if (event.charCode !== 0)

 _keyPress(event: any) {
    if (event.charCode !== 0) {
      const pattern = /[0-9\+\-\ ]/;
      const inputChar = String.fromCharCode(event.charCode);

      if (!pattern.test(inputChar)) {
        // invalid character, prevent input
        event.preventDefault();
      }
    }
  }


回答4:

We can use pattern to validate mobile number in angular.

<form #userInfoForm="ngForm">
    <input type="text" name="mobile" ngModel placeholder="MOBILE NUMBER" [pattern]="'[789][0-9]{9}'">
</form>
<div class="btn-wrp">
   <button (click)="submit(userInfoForm)">Submit</button>
</div>

In typescript I check whether form is valid or not and sent error message

submit(userDetailsForm: NgForm) {
    if(userDetailsForm.invalid){
       this.toastr.error('Please enter valid details');
       return false;
    }else{
       this.router.navigate(["frontend/car/quotes"]);
    }
}


回答5:

try this code...... typescript code ..

  form: FormGroup;
  pattern1 =  "^[0-9_-]{10,12}";
  constructor(public fb: FormBuilder) {
    this.form = this.fb.group({
      phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
    })
  }

html code..

<form [formGroup]="form">
  <input type="text" formControlName="phone">
  <ng-container *ngIf="form.controls.phone.errors">
   <ng-container *ngIf="form.controls.phone.errors.pattern">
    phone no is not statndard patter
    </ng-container>
      <ng-container *ngIf="form.controls.phone.errors.required">
    phone no is required
    </ng-container>
  </ng-container>

</form>


标签: angular