2

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?

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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();
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.