Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict an input to only accept numbers?

I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.

<input type="text" name="inputName" data-ng-change="numbersOnly()"/> 

The problem is that I need to target the input that triggered numbersOnly() so that I can remove the letters entered. I have looked long and hard on Google and was unable to find anything regarding this.

What can I do?

like image 320
Chris Bier Avatar asked Jan 30 '13 22:01

Chris Bier


2 Answers

Easy way, use type="number" if it works for your use case:

<input type="number" ng-model="myText" name="inputName"> 

Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

Hackish? way, $watch the ng-model in your controller:

<input type="text"  ng-model="myText" name="inputName"> 

Controller:

$scope.$watch('myText', function() {    // put numbersOnly() logic here, e.g.:    if ($scope.myText  ... regex to look for ... ) {       // strip out the non-numbers    } }) 

Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945

All of the above solutions involve using ng-model, which make finding this unnecessary.

Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)

like image 176
Mark Rajcok Avatar answered Oct 10 '22 18:10

Mark Rajcok


Using ng-pattern on the text field:

<input type="text"  ng-model="myText" name="inputName" ng-pattern="onlyNumbers"> 

Then include this on your controller

$scope.onlyNumbers = /^\d+$/; 
like image 26
MarkJ Avatar answered Oct 10 '22 19:10

MarkJ