In this tutorial, we will learn Textbox Should Accept only Numbers in Angular. We will use the number validation pattern in angular 6, angular 7, angular 8, and angular 9 applications.


Follow this step by step guide below:



Solution:

Only accepts number use this partern

this.form = fb.group({
  number: ['', [Validators.required, Validators.pattern("^[0-9]*$")]]
})



Example:

src/app/app.component.html

<div class="container">
    <h1>Angular Validation for Number Only - rathorji.in</h1>   
    <form [formGroup]="form" (ngSubmit)="submit()">
        <div class="form-group">
            <label for="number">Number</label>
            <input 
                formControlName="number"
                id="number" 
                type="text" 
                class="form-control">
            <div *ngIf="f.number.touched && f.number.invalid" class="alert alert-danger">
                <div *ngIf="f.number.errors.required">Number is required.</div>
                <div *ngIf="f.number.errors.pattern">Enter only number.</div>
            </div>
        </div>
        <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>
    </form>
</div>



src/app/app.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms'; 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup = new FormGroup({});
  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      number: ['', [Validators.required, Validators.pattern("^[0-9]*$")]]
    })
  }

  get f(){
    return this.form.controls;
  }
  submit(){
    console.log(this.form.value);
  }
}


May this example help you.