DEV Community

Pankaj Kumar
Pankaj Kumar

Posted on

Allow Only Numbers in Textbox in Reactive Form Angular

For several reasons, we need to validate the input field to enter only numbers. In this article, we will see how to allow users to enter only numbers in the input area in angular application. To use the below approach a developer should have basic understanding of reactive form.

Here in the example below, I will use a Reactive form. The same will work for angular 6, angular 7, angular 8, and further versions.

At first import Reactive form module in module.ts file


imports: [

....

ReactiveFormsModule

...

],

Enter fullscreen mode Exit fullscreen mode

Now, let's have a look at the code inside component.ts file


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, FormArray, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `<div class="container">
    <form [formGroup]="addForm" (ngSubmit)="submit()">
    <div class="form-group">
    <label for="mobile">Mobile</label>
    <input formControlName="mobile" id="mobile" type="text" class="form-control">
    <div *ngIf="f.mobile.touched && f.mobile.invalid" class="alert alert-danger">

    <div *ngIf="f.mobile.errors.required">mobile is required.</div>
    <div *ngIf="f.mobile.errors.pattern">Enter only number.</div>
    </div>
    </div>
    <button class="btn btn-primary" type="submit">Submit</button>
    </form>
   </div>`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
  addForm:FormGroup;
  constructor(
    private fb : FormBuilder
  ){ }

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

  get f(){
    return this.addForm.controls;
  }

}

Enter fullscreen mode Exit fullscreen mode

Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.

This article is originally posted over jsonworld

Top comments (0)