MattDionis
MattDionis

Reputation: 3616

Validate input type="number" before submitting

I'm running into an interesting problem while trying to restrict user input to a number.

My HTML looks like so:

<input name="activeDate" type="number" class="form-control" ng-model="account.tag.activeDate"></input>

...and my relevant Angular controller code like so(this is inside a click handler):

tag.activeDate = moment.utc().add(tag.activeDate, tag.tagDurationType).toISOString();

Unfortunately when I click the button which submits my form and calls that click handler I get this error in my console:

[ngModel:numfmt] Expected `2015-08-27T22:09:18.919Z` to be a number

Looks like my input is checked upon submitting, when it's converted to a date within my controller. How do I limit user input to numbers without running into this?

Upvotes: 2

Views: 105

Answers (2)

Dave M
Dave M

Reputation: 418

Select your input element, then do the following you have to look up value of number0Key and number9Key:

myElement.on("keypress", function(e) {
  if (e.which < number0Key || e.which > number9Key) {
    e.stopPropagation();
  }
});

Upvotes: 0

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

Use ng-pattern="/^(\d)+$/" - it's simple regex expression

var app = angular.module('num', []);

app.controller('numCtrl', function($scope, $http){
  $scope.digits = {};
});
angular.bootstrap(document.body, ['num']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="numCtrl">
    <form class="digits" name="digits" ng-submit="getGrades()" novalidate >
      <input type="text" placeholder="digits here plz" name="nums" ng-model="nums" required ng-pattern="/^(\d)+$/" />
      <p class="alert" ng-show="digits.nums.$error.pattern">Numbers only, please.</p> 
      <br>
      <input class="btn" type="submit" value="Do it!" ng-disabled="!digits.$valid" />
    </form>
  </body>

Upvotes: 2

Related Questions