Angular Custom Directives: Accept number only and restrict special characters in Input field

Anas Reza
2 min readAug 17, 2020

--

Wondering how to restrict your input field to accept number only?

Sometimes, you apply <input type="number"> and ended up with a thought of having it solved, but that’s not the case.

You may see strange behavior of input field with type=”number”. Initially when you start writing in field, you won’t get to enter character a, b, e or anything else but when you write in a way like 123eeww it accepts because it becomes an exponential value.
Going back to the basics, that we normally doesn’t give the attention to, always have the answer.

The type number only accepts floating-point-numbers and e or E character after number(which represent exponents if used after number like 123ee). What now?

To avoid such cases and strictly implement only number type, we have to create custom directive which can be even helpful across the application level. Below is the snippet:

Explanation:

As you can see above,
Step 1: onKeyPress event, we check for entered character if it matches the given regex ‘^[0–9]+$’, if not input won’t accept that character
Step 2
: what if someone copy and paste the data?, to avoid such scenario we can restrict the paste event as well such that it only accepts number format only and replaced the rest non numeric characters with ‘’.

How to apply?
Just go to your html and add selector of directive to your field:
<input type="number" numbersOnly>

How to restrict only special characters in your input field?

The only thing you need to change is regex:
regexStr = ‘^[a-zA-Z0–9 _]*$’

Use the code explained above and change the regex, you will have your restricted special characters input field.

What if you want to customize regex basis on your need

Suppose if I want to allow ‘-’, ‘#’ only as special character and restrict the rest.

^[a-zA-Z0–9 _-#]*$: Just keep adding those at the end of regex and it will work like a charm.

--

--