Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 665
Yulian Avatar asked Mar 15 '16 11:03

Yulian


2 Answers

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}}"/>
like image 51
Hadi J Avatar answered Oct 01 '22 11:10

Hadi J


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

like image 24
Mohaimin Moin Avatar answered Oct 01 '22 11:10

Mohaimin Moin