Askar Ibragimov Askar Ibragimov -5 years ago 203
AngularJS Question

Directive restricting input is not working with type=number

I have a custom directive that restricts input to specific symbols, in my case, only numbers. It is made after angularjs filters on ng-model in an input and it works fine in text-type inpit.

Directive declared as

.directive('onlydigitinput', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue.toLowerCase().replace(/ /g, '').replace(/[^0-9]+/g, '');
if (transformedInput != inputValue) {
return transformedInput;

but in case of numerical input I want to use input type=number, not type=text:

<input type="number"
onlydigitinput="onlydigitinput" required="required" min="1" max="99" maxlength="2">

and then it's a problem: I have correct validation based on min-max attribute, but I still can enter all symbols, such as letters, and directive does not work as it should. Additionally, maxlength seems not to have effect. How I can possibly fix my directive to work with type="number" inputs?

Answer Source

There are two issues here. First, the maxlength attribute doesn't work with input type number. See e.g. maxlength ignored for input type=“number” in Chrome.

Second, when the input type is number, your directive's function only gets a value for the inputValue parameter when it's a number. See this fiddle as an example (the console output might make it clearer).


How crucial is it for you to use the number type input? If the spinner controls that browsers add to the input field for it aren't a necessity, I'd probably go for a custom type like described here: How to create a custom input type in Angular.js?

I've used something very similar for e.g. money input fields (with localized decimal separators etc.).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download