Input Masking

In this lesson, we'll look at a concept called input masking.

We’re almost finished with the form. One common feature in forms is to require a specific format for inputs. For example, most expiration dates have a forward slash to separate the day and month. That’s precisely what we’re expecting from the expiration date input in our form.

However, there is a problem with this. Currently, there is no way for the user to know the format we expect from them. While expiration dates are standard in checkout forms around the world, we may have a user who doesn’t know how to format the date. If they input an invalid value, they’ll receive a generic message. They won’t know anything about the expected format.

Input masks

This is where a feature called input masks comes into play. Input masking is the process of constraining user input. They’re a great way to reduce confusion as to why an input value may be incorrect, while also making sure data is in the required format.

We can use an input mask to deny the user from inputting alphabetic characters. We can also help them by adding the forward slash after two digits. It’s a great way to provide a better user experience.

Installing NGX mask

There are two ways to approach this. We can manually perform input masking, or we can use a library. Manually achieving input masking will require a lot of work because there are a lot of edge cases to consider. We’ll go with the library route.

There’s a great library called NGX Mask. It’s a plugin for Angular that will help us with input masking. It’s effortless to install and use.

First, we’ll need to install the library. In the command line, run the following command:

npm install --save ngx-mask

The NGX mask library conveniently comes in a module. We’ll need to register it with our application for access to its features. We’ll register it in the app.module.ts module file.

Update it to the following:

Get hands-on with 1200+ tech skills courses.