Clean characters from input type number – Angular

So you want to use the new input type="number" because well, it's cool. It already prevents user from entering characters other than digits. Plus, on mobile it will show a numpad instead of the regular keyboard.

What's the problem?

The problem is, the type="number" will allow the user to enter characters like: +, - and e

In case you don't want to do that, you can clean it in real time using a custom directive. Notice we will be using the type="tel" instead 😉

Markup

I'll be using my custom directive as an attribute and also using maxlength="X", an attribute that does nothing in type="tel" inputs but will be useful with my custom directive.

<input number-input maxlength="4" ng-model="XYZ" type="tel">

Directive

We get the value, clean it with a regular expression and cut it to the maxlength value or 4 (as default)

return {
  require: 'ngModel',
  link: function (scope, element, attr, ngModelCtrl) {
    function fromUser(text) {

      var transformedInput = text.trim().replace(/[^0-9]/g, ''),
        maxlength = attr.maxlength || 4;

      transformedInput = transformedInput.substring(0, maxlength);

      if (transformedInput !== text) {
        ngModelCtrl.$setViewValue(transformedInput);
        ngModelCtrl.$render();
      }
      return transformedInput;
    }
    ngModelCtrl.$parsers.push(fromUser);
  }
};

Enjoy.

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
2 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*