Yulian
Yulian

Reputation: 6759

How to allow only integer numbers in Angular?

I have a number input in my HTML and I want it to be an integer, not a floating point number.

So, if I have this:

<input type="number" ng-model="person.age" />

Angular will consider a value of 18.4 to be valid. How can I fix this?

Upvotes: 14

Views: 38810

Answers (5)

gadildafissh
gadildafissh

Reputation: 2402

Here is another option that works great for me. It doesn't allow the user to enter non integer values, but intercepts the keyboard entries if invalid and prevents the character from being typed.

<input type="number" min="0" oninput="validity.valid||(value='');" maxlength="3" placeholder="Quantity"/>

Upvotes: 0

Alvaro ML
Alvaro ML

Reputation: 31

I will share part of my code.
In my .ts file I have the following code:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
...
export class IntegerComponent implements OnInit {
fgInteger: FormGroup;
...
constructor(private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.fgInteger = this.formBuilder.group({
      amount: ['', [Validators.required, ..., Validators.pattern('^\\d+$')]]
    });
  }
}

The pattern into the .ts worked for me:

  • '^' This is the start of the pattern.
  • '\d' This means that the value is a digit (0-9).
  • '+' Means that this pattern should be used more than 1 time.
  • '$' This is the end of the pattern.

Also, into my .html file, I have the following code:

<form id="fgInteger" [formGroup]="fgInteger" novalidate #fform="ngForm" (ngSubmit)="onSubmit()">
     <mat-form-field appearance="outline">
          <mat-label>Amount:</mat-label>
          <input name="amount" formControlName="amount" type="number" min="1" step="1" matInput placeholder="Enter the amount.">
     </mat-form-field>
 </form>

By the way I'm working with Angular Material.

Upvotes: 3

ian korkie
ian korkie

Reputation: 53

This worked for me.

<input type="number" step="1" min="0">

Upvotes: 1

Hadi
Hadi

Reputation: 17289

function Main($scope) {

     $scope.regex = "/^-?[0-9][^\.]*$/";
   }
input.ng-dirty.ng-invalid { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="Main">
        <form name="form">
	  <input type="number" ng-model="person.age" ng-pattern="/^-?[0-9][^\.]*$/"/>
           <input type="number" ng-model="person.age1" ng-pattern="{{regex}}" />
        </form>
    </div>
</div>

try this

 $scope.regex = "/^-?[0-9][^\.]*$/";

<input type="number" ng-model="person.age" ng-pattern="{{regex}}"/>

Upvotes: 19

Mohaimin Moin
Mohaimin Moin

Reputation: 841

You can also use this ng-pattern="/^(0|\-?[1-9][0-9]*)$/".

Upvotes: 2

Related Questions