Ossama Benbouidda Ossama Benbouidda - 5 months ago 11
AngularJS Question

Limit the user's input in an input number to 4 digits

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.

Answer

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