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">Code language: HTML, XML (xml)

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);
  }
};Code language: PHP (php)

Enjoy.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *