2

I'm having trouble to restrict an input type number to positive number only. As stated in that post : HTML5: number input type that takes only integers? I am not looking for the step="1" answer since it allows the user to type {e.,} as well.

I am using a directive I found on a related post (How do I restrict an input to only accept numbers?) to which I just added a few console log and a toString() :

It's working fine when the input type is a text, however it's never called when the input type is number and I type either 'e' ',' or '.'.

Any idea on what I am missing here ? I want to use the input type=number to enable the arrow to select a value using angular material.

function restrictInput($mdDialog) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ctrl) {
      function inputValue(value) {
        console.log("hello ! :", value)
        var val = value.toString();
        console.log("goodbye ! : ", val)
        if (val) {
          var digits = val.replace(/[^0-9]/g, '');
          console.log("digits :", digits)
          console.log("val : ", val)
          if (digits !== val) {
            ctrl.$setViewValue(digits);
            ctrl.$render();
          }
          return parseInt(digits, 10);
        }
        return undefined;
      }
      ctrl.$parsers.push(inputValue);
    }
  };
}

Html is something like this :

<md-input-container flex class="md-input-has-placeholder">
  <label>Années d'expérience stage inclus</label>
    <input
      type="number"
      required
      step="1"
      restrict-input
      min="0"
      name="Expérience stage"
      ng-model="model">
    <div ng-messages="form['Expérience stage'].$error" md-auto-hide="false">
      <div ng-message="required">Requis</div>
    </div>
</md-input-container>

EDIT

Using getter setter (ng-model-options="{ getterSetter: true }") worked out perfectly here.

Community
  • 1
  • 1
  • write a watch for $scope.model and restrict the input and replace it there – M14 Nov 15 '16 at 09:47
  • 2
    `` is a start for numeric values. Then you just have to check it's not a letter. Also see http://stackoverflow.com/questions/7372067/is-there-any-way-to-prevent-input-type-number-getting-negative-values – maxime1992 Nov 15 '16 at 09:51

1 Answers1

3

You don't need to use directive if just need to restrict input type "number" to accept only integer.

<input type="number" ng-pattern="/^(0|[1-9][0-9]*)$/" >

Can you type above code in your app?

This will only accept numbers.

Avinash Rathod
  • 590
  • 4
  • 15