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.

Directive

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

Enjoy.

Tags:

2 Responses to “Clean characters from input type number – Angular”

  1. Anthony Tornambe August 10, 2016 at 9:44 am #

    It’s very helpful code.

    • Rick August 10, 2016 at 9:45 pm #

      Glad it helped you.

Leave a Reply

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