React Components with Phil Next

Masked Input

Have you ever seen a web form that asks for something like a phone number, a credit card, a license code... and as you're typing in the value, you notice it isn't just a regular old text box.

For example, it automatically inserts brackets around an area code and hyphens between digit groupings, and so on.

The control is called Masked Input and it's super easy to build in React. I'm going to show you how...

Requirements

Our control is going to take all the same fields you'd expect on a text input control In addition, it's going to take a mask.

The mask is just a string that defines the format of the digit groups. we'll use the number sign as placeholders for where the digits will go. all other characters in the mask will appear in the MaskedInput control.

example masks

Design

Picture a standard controlled input element on a form. In order to display a modified value (without changing the underlying data), we need to insert ourselves between the form and the input. We'll receive raw data from the parent... and we'll tell the input control to display our formatted value. We'll also intercept onChange so we can remove the formatting so the parent only sees the raw data.

example masks

Programming

Watch the video or download the project files

Wrap up

Our masked input control only accepts digits. With a little work you could extend it to also take letters, hexidecimal values, etc.

Exercises

  1. (easy) Rewrite your Masked Input control to accept hexadecimal digits using a capital X as placeholder. Example mask: "XXXX XXXX"

  2. (harder) Extend your Masked Input control to accept letters and digits. Use # for a digit; and A for a letter. Example mask: a Canadian postal code is "A#A #A#". Don't forget your unit tests!

Bonus Content: Source Code and Unit Tests

The full source code including unit tests and solutions for both exercises are available for download exclusively by mailing list members. Also as a list member you'll get articles about modern web development topics like React, Redux, TypeScript, etc. emailed to you occasionally.

Download the Source Code

and sign up for free articles, tutorials, sample code, and more videos!