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 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.
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.
Share Improve this question asked Jul 7, 2016 at 14:58 MathemagicianMathemagician 5071 gold badge10 silver badges20 bronze badges 6 | Show 1 more comment5 Answers
Reset to default 6Here 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
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"
Using ng-pattern
with a regex
\d : digits
{4} : 4 times
<input type="number" ng-pattern="/^\d{4}$/" />
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" />
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();
});
}
});
maxlength
is not a valid attribute for a Number input – Jeff Noel Commented Jul 7, 2016 at 15:04