1

How can I prevent (usign maybe Angular) the user from entering more than 4 numbers in a an simple number like this one :

<input type="number">

I used ng-maxlength, and max attributes, but those attributes as specified by w3.org specs and the official website Angular, do not prevent the user from adding more numbers.

What I want is that the input stops in 4 digits, like adding in somehow a mask or something to it.

Mathemagician
  • 497
  • 1
  • 10
  • 19

5 Answers5

6

Here is a way to do it using JavaScript:

HTML

<input type="number" oninput="checkNumberFieldLength(this);">

JavaScript

function checkNumberFieldLength(elem){
    if (elem.value.length > 4) {
        elem.value = elem.value.slice(0,4); 
    }
}

I would also suggest to make use of the min and max HTML attributes for the input Number element, if it applies in your case.

JSFiddle

W3c: input Number

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
4

Well, as somebody stated above maxlength doesn't work with inputs of type number, so you can do it this way:

<input type="text" pattern="\d*" maxlength="4">

of course, this will do if it's not a requirement to have input type="number"

Vi100
  • 4,080
  • 1
  • 27
  • 42
2

Using ng-pattern with a regex

\d : digits

{4} : 4 times

<input type="number" ng-pattern="/^\d{4}$/" />
Weedoze
  • 13,683
  • 1
  • 33
  • 63
1

I would create a function in your controller like this

angular.module("my-app", [])
    .controller('my-controller', function($scope) {
        $scope.checkInput = function() {
            if (input.value.length > 4) {
                input.value = input.value.slice(0,4);
            }
        });
    });

Then in your view you can do something like this

<input type="number" max="9999" ng-input="checkInput()" />

Warning: The max attribute will only work for the spinner. The user will still be able to enter numbers higher than that. Here's an example

<input type="number" max="9999" />
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

You can do that using modernizr and jquery.

I've made an example here: https://jsfiddle.net/5Lv0upnj/

$(function() {
    // Check if the browser supports input[type=number]
    if (Modernizr.inputtypes.number) {
        $('input[type=number]').keypress(function(e) {
            var $this = $(this),
                maxlength = $this.attr('maxlength'),
                length = $this.val().length;

            if (length >= maxlength)
                e.preventDefault();
        });
    }
}); 
Wilmer
  • 138
  • 1
  • 8