Angular 4 Mobile number validation

2020-06-17 14:26发布

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>

标签: angular
5条回答
放我归山
2楼-- · 2020-06-17 15:02

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"]);
    }
}
查看更多
Anthone
3楼-- · 2020-06-17 15:04

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>
查看更多
唯我独甜
4楼-- · 2020-06-17 15:11

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

查看更多
ゆ 、 Hurt°
5楼-- · 2020-06-17 15:14
<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();
    }
  }
查看更多
萌系小妹纸
6楼-- · 2020-06-17 15:21

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();
      }
    }
  }
查看更多
登录 后发表回答