Ossama Benbouidda Ossama Benbouidda - 3 months ago 8
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
, and
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.


Here is a way to do it using JavaScript:


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


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.