3

How can I prevent typing anything except digits (integers) into an input field with angularJS

type="number" allows floating point numbers

I also tried several regexes with ng-pattern, but those floating points were still allowed, although I explicitly specified digits only.

I'm fiddling with watchers at the moment, but can't make them work properly, at least not yet. I'm thinking of writing keydown event handlers for these fields, but still hoping there's better way.

Eedoh
  • 5,818
  • 9
  • 38
  • 62

5 Answers5

2

This will make the input to a stepMitchMatch if entering something like 1.4

Regex pattern is unnecessary as you can do it with common attributes

:invalid{
  background: red
}
:valid{
  background: lime
}
<input type="number" step="1">

If you need to overdo it, then use angular-ui/mask with 9?9?9?9?9?9?9?9?9?9? as the masked value

Endless
  • 34,080
  • 13
  • 108
  • 131
  • it does not prevent entering floating numbers. You are still able to write floating numbers but the input will become invalid, – Endless Jun 08 '16 at 13:31
  • 1
    OP has made it very clear that he does not want to allow user to "type" anything other than digits. So everything else becomes irrelevant. – fahadash Jun 08 '16 at 14:02
  • Sure, if you want to overdo simple things then your way is the right solution. think it's more worth spending time on validating on the server side anyway. it's enough to know that you entered it wrong and that you should correct it – Endless Jun 08 '16 at 14:09
0

Try this:

<input type="number" step="1" ng-pattern="^[0-9]+$">

The regex will fail anything other then a round integer and the step will automatically make the up/down arrows add/subtract 1

Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
0

You can use a regex string within ng-pattern to validate your input.

ng-pattern="^-?[0-9]*$"

If you want to only allow positive numbers, remove the "-?"

You can also test out your patterns at the bottom of this page: https://docs.angularjs.org/api/ng/directive/ngPattern

Edit:

I missed that you want to prevent users from typing invalid characters. There's an solution over here: https://stackoverflow.com/a/28975658/6440513 that answers your question, and you can use the regex pattern within the directive provided there.

Community
  • 1
  • 1
I.F.
  • 9
  • 3
-1

You can use ng-pattern to resolve this

<input type="number" ng-pattern="/^[0-9]{1,7}$/">

This will let you enter numbers in the range of 0-9999999

Webdev
  • 617
  • 6
  • 24
-1

Create a directive may be?

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='number' step='1' />",
    replace: true,
    link: function(scope, e, attrs) {    
      e.bind("keydown", function(e) {

        if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
          e.preventDefault();
        }
      });
    }
  };
});

then use it in your app like so

<div ng-app="myApp">
 <my-number><my-number>
</div>

You can garnish it further to allow bindings, and special keys

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='text' ng-model='model' />",
    replace: true,
    scope: {model : "="},
    link: function(scope, e, attrs) {

      e.bind("keydown", function(e) {
        // Special request from @endless for all these keys to be exempted
        //
        if (e.ctrlKey || e.altKey || e.keyCode >= 0 && e.keyCode <= 31 || e.keyCode >= 33 && e.keyCode <= 40 || e.keyCode==46) {
          return;
        }
        else if (!(e.ctrlKey || (e.keyCode >= 48 && e.keyCode <= 57 && !e.shiftKey))) {
          e.preventDefault();
        }
      }).bind("change", function() {
         var e = angular.element(this);
         if (isNaN(parseInt(e.val())) || e.val().indexOf(".") >= 0) {
            alert("incorrect number value entered");
            e.val("");
         }
      });
    }
  };
});

Here is a working plunkr example

Here is another fork of the above that allows all the special keys

Here is more info on directives

fahadash
  • 3,133
  • 1
  • 30
  • 59
  • 2
    The element is already wrapped in jqLite, you don't have to do it yourself, i'd also advice using a `input[type="number"]` for the keyboard controls – Martijn Welker Jun 08 '16 at 14:09
  • Think it would be better to use attribute instead of a custom directive, what if you want to add required? – Endless Jun 08 '16 at 14:10
  • better to use validation pipeline, this don't work if you paste in the value – Endless Jun 08 '16 at 14:10
  • @MartijnWelker jqLite when sees another jq object in the selector, simply returns it as is. But you are right, there is no point in having it that way. I modified my answer – fahadash Jun 08 '16 at 14:14
  • @Endless This example is just to show one way to do what OP is trying to achieve. It is not a full app, he can certainly fix things up for his needs. I feel that you are using downvote because of feud that you carry due to my comments on your answer. I did not downvote yours. – fahadash Jun 08 '16 at 14:23
  • @Endless I also updated the plunker to take care of the paste issue. May not be the best way, but one of the ways. – fahadash Jun 08 '16 at 14:23
  • I could still paste in `2.2` and one other bad thing was that you can't use backspace, arrow, delete to ctrl+a or any other keybord inputs, yet an other reason to use validation pipeline and another reason for me to downvote this – Endless Jun 08 '16 at 14:26
  • @Endless I fixed those problems, you wanna take your downvote off now? – fahadash Jun 08 '16 at 14:35
  • didn't see any changes – Endless Jun 08 '16 at 14:39
  • @Endless It was updated in plunkr, I also have added that to the answer. – fahadash Jun 08 '16 at 14:44
  • The directive worked just fine. Thank you. Accepting this answer. I don't get why people downvoted it :S. – Eedoh Jun 08 '16 at 17:05
  • @Eedoh cuz it doesn't work any good, you can not edit the field, only append numbers, it literally disables all others keyboard shortcuts. Like tabbing to the next input field - impossible – Endless Jun 08 '16 at 17:36
  • @Endless I took care of the special keys. Tab it, arrow it, backspace it, delete it. check the plunkr as well as the answer. Are you ready to let go of your ego now? – fahadash Jun 09 '16 at 02:19