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.

5 Answers 5

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

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

3 Comments

it does not prevent entering floating numbers. You are still able to write floating numbers but the input will become invalid,
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.
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
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

1 Comment

OP wants typing of anything other than digits disabled.
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.

Comments

-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

13 Comments

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
Think it would be better to use attribute instead of a custom directive, what if you want to add required?
better to use validation pipeline, this don't work if you paste in the value
@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
@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.
|
-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

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.